2023-10-25 04:14:32 +00:00
|
|
|
// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2023-12-22 22:59:19 +00:00
|
|
|
_ "embed"
|
2023-10-25 04:14:32 +00:00
|
|
|
|
|
|
|
_ "modernc.org/sqlite"
|
|
|
|
)
|
|
|
|
|
2023-12-22 22:59:19 +00:00
|
|
|
//go:embed sql/schema.sql
|
|
|
|
var schema string
|
2023-10-25 04:14:32 +00:00
|
|
|
|
|
|
|
// Open opens a connection to the SQLite database
|
|
|
|
func Open(dbPath string) (*sql.DB, error) {
|
|
|
|
return sql.Open("sqlite", dbPath)
|
|
|
|
}
|
|
|
|
|
2023-12-22 22:59:19 +00:00
|
|
|
// VerifySchema checks whether the schema has been initalised and initialises it
|
|
|
|
// if not
|
|
|
|
func InitialiseDatabase(dbConn *sql.DB) error {
|
|
|
|
var name string
|
|
|
|
err := dbConn.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name='schema_migrations'").Scan(&name)
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-10-25 04:14:32 +00:00
|
|
|
tables := []string{
|
|
|
|
"users",
|
|
|
|
"sessions",
|
|
|
|
"projects",
|
2023-12-22 22:59:19 +00:00
|
|
|
"releases",
|
2023-10-25 04:14:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, table := range tables {
|
|
|
|
name := ""
|
2023-12-22 22:59:19 +00:00
|
|
|
err := dbConn.QueryRow(
|
|
|
|
"SELECT name FROM sqlite_master WHERE type='table' AND name=@table",
|
|
|
|
sql.Named("table", table),
|
|
|
|
).Scan(&name)
|
2023-10-25 04:14:32 +00:00
|
|
|
if err != nil {
|
2023-12-22 22:59:19 +00:00
|
|
|
if err = loadSchema(dbConn); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-10-25 04:14:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-12-22 22:59:19 +00:00
|
|
|
// loadSchema loads the initial schema into the database
|
|
|
|
func loadSchema(dbConn *sql.DB) error {
|
|
|
|
if _, err := dbConn.Exec(schema); err != nil {
|
2023-10-25 04:14:32 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-12-22 22:59:19 +00:00
|
|
|
return nil
|
2023-10-25 04:14:32 +00:00
|
|
|
}
|