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// Embed the schema into the binary
15//
16//go:embed sql
17var embeddedSQL embed.FS
18
19// Open opens a connection to the SQLite database
20func Open(dbPath string) (*sql.DB, error) {
21 return sql.Open("sqlite", dbPath)
22}
23
24func VerifySchema(dbConn *sql.DB) error {
25 tables := []string{
26 "users",
27 "sessions",
28 "projects",
29 }
30
31 for _, table := range tables {
32 name := ""
33 err := dbConn.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name=?", table).Scan(&name)
34 if err != nil {
35 return err
36 }
37 }
38 return nil
39}
40
41// LoadSchema loads the schema into the database
42func LoadSchema(dbConn *sql.DB) error {
43 schema, err := embeddedSQL.ReadFile("sql/schema.sql")
44 if err != nil {
45 return err
46 }
47
48 _, err = dbConn.Exec(string(schema))
49
50 return err
51}