DEVELOPMENT ENVIRONMENT

~liljamo/felu

ref: 1ff229ca02df09c551a4d0ecc82471fa47168812 felu/internal/db/db.go -rw-r--r-- 1.3 KiB
1ff229caJonni Liljamo feat: add tsigkey field to domains 17 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

// Package db implements database migrations and manipulation utilities.
package db

import (
	"database/sql"
	"log/slog"

	"git.src.quest/~liljamo/felu/internal/config"
	// nolint
	_ "github.com/mattn/go-sqlite3"
)

// DBConn is a global for accessing the database connection.
var DBConn *sql.DB

// InitDB initializes the programs database.
func InitDB() error {
	var err error
	DBConn, err = sql.Open("sqlite3",
		config.FeluConfig.DataDir+"felu.db?_foreign_keys=true")
	if err != nil {
		return err
	}

	runMigrations()

	return nil
}

// InitAdminUser initializes the programs admin user.
//
// Errors out if at least one admin user already exists.
func InitAdminUser() error {
	rows, err := DBConn.Query(`SELECT id FROM users WHERE is_admin = TRUE`)
	if err != nil {
		return err
	}
	defer rows.Close()
	if rows.Next() {
		// There is at least one...
		slog.Info("Existing admin user found")
		return nil
	}

	// Since we're here, it's assumed no admin accounts exist
	slog.Info("Creating initial admin user")
	err = CreateAdmin(config.FeluConfig.InitialAdminEmail, config.FeluConfig.InitialAdminPwd)
	if err != nil {
		return err
	}
	return nil
}