release.go

 1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
 2//
 3// SPDX-License-Identifier: Apache-2.0
 4
 5package db
 6
 7import (
 8	"database/sql"
 9	"fmt"
10	"sync"
11)
12
13// UpsertRelease adds or updates a release for a project with a given ID in the
14// database.
15func UpsertRelease(db *sql.DB, mu *sync.Mutex, id, projectID, url, tag, content, date string) error {
16	mu.Lock()
17	defer mu.Unlock()
18
19	_, err := db.Exec(`INSERT INTO releases (id, project_id, url, tag, content, date)
20		VALUES (?, ?, ?, ?, ?, ?)
21		ON CONFLICT(id) DO 
22			UPDATE SET
23				url = excluded.url,
24				content = excluded.content,
25				tag = excluded.tag,
26				content = excluded.content,
27				date = excluded.date;`, id, projectID, url, tag, content, date)
28	if err != nil {
29		return fmt.Errorf("failed to execute SQL: %w", err)
30	}
31
32	return nil
33}
34
35// GetReleases returns all releases for a project with a given id from the database.
36func GetReleases(db *sql.DB, projectID string) ([]map[string]string, error) {
37	rows, err := db.Query(`SELECT id, url, tag, content, date FROM releases WHERE project_id = ?`, projectID)
38	if err != nil {
39		return nil, fmt.Errorf("failed to query database: %w", err)
40	}
41	defer rows.Close()
42
43	releases := make([]map[string]string, 0)
44	for rows.Next() {
45		var (
46			id      string
47			url     string
48			tag     string
49			content string
50			date    string
51		)
52
53		err := rows.Scan(&id, &url, &tag, &content, &date)
54		if err != nil {
55			return nil, fmt.Errorf("failed to scan row: %w", err)
56		}
57
58		releases = append(releases, map[string]string{
59			"id":         id,
60			"project_id": projectID,
61			"url":        url,
62			"tag":        tag,
63			"content":    content,
64			"date":       date,
65		})
66	}
67
68	return releases, nil
69}