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"
|
2024-02-23 23:06:16 +00:00
|
|
|
"errors"
|
|
|
|
"sync"
|
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
|
|
|
|
2024-02-23 23:06:16 +00:00
|
|
|
var mutex = &sync.Mutex{}
|
|
|
|
|
2023-10-25 04:14:32 +00:00
|
|
|
// Open opens a connection to the SQLite database
|
|
|
|
func Open(dbPath string) (*sql.DB, error) {
|
2024-02-23 23:06:16 +00:00
|
|
|
return sql.Open("sqlite", "file:"+dbPath+"?_pragma=journal_mode%3DWAL")
|
2023-10-25 04:14:32 +00:00
|
|
|
}
|
|
|
|
|
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
|
2024-02-23 23:06:16 +00:00
|
|
|
err := dbConn.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name='users'").Scan(&name)
|
|
|
|
if err != nil && errors.Is(err, sql.ErrNoRows) {
|
|
|
|
mutex.Lock()
|
|
|
|
defer mutex.Unlock()
|
|
|
|
if _, err := dbConn.Exec(schema); err != nil {
|
|
|
|
return err
|
2023-10-25 04:14:32 +00:00
|
|
|
}
|
2024-02-23 23:06:16 +00:00
|
|
|
return nil
|
2023-10-25 04:14:32 +00:00
|
|
|
}
|
2024-02-23 23:06:16 +00:00
|
|
|
return err
|
2023-10-25 04:14:32 +00:00
|
|
|
}
|