db.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	_ "embed"
10
11	_ "modernc.org/sqlite"
12)
13
14//go:embed sql/schema.sql
15var schema string
16
17// Open opens a connection to the SQLite database
18func Open(dbPath string) (*sql.DB, error) {
19	return sql.Open("sqlite", dbPath)
20}
21
22// VerifySchema checks whether the schema has been initalised and initialises it
23// if not
24func InitialiseDatabase(dbConn *sql.DB) error {
25	var name string
26	err := dbConn.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name='schema_migrations'").Scan(&name)
27	if err == nil {
28		return nil
29	}
30
31	tables := []string{
32		"users",
33		"sessions",
34		"projects",
35		"releases",
36	}
37
38	for _, table := range tables {
39		name := ""
40		err := dbConn.QueryRow(
41			"SELECT name FROM sqlite_master WHERE type='table' AND name=@table",
42			sql.Named("table", table),
43		).Scan(&name)
44		if err != nil {
45			if err = loadSchema(dbConn); err != nil {
46				return err
47			}
48		}
49	}
50	return nil
51}
52
53// loadSchema loads the initial schema into the database
54func loadSchema(dbConn *sql.DB) error {
55	if _, err := dbConn.Exec(schema); err != nil {
56		return err
57	}
58	return nil
59}