Add SQLite file creation

This commit is contained in:
Andrew-71 2024-10-12 21:58:42 +03:00
parent cda8f0cc1b
commit 82aba0c9e9
2 changed files with 13 additions and 8 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
pye pye
private.key private.key
dev-data.db dev-data.db
data.db

View file

@ -58,10 +58,9 @@ func (s SQLiteStorage) EmailExists(email string) bool {
} }
func MustLoadSQLite(dataFile string) SQLiteStorage { func MustLoadSQLite(dataFile string) SQLiteStorage {
// I *think* we need some file, even if only empty
if _, err := os.Stat(dataFile); errors.Is(err, os.ErrNotExist) { if _, err := os.Stat(dataFile); errors.Is(err, os.ErrNotExist) {
slog.Error("sqlite3 database file required", "file", dataFile) os.Create(dataFile)
os.Exit(1) slog.Info("created sqlite3 database file", "file", dataFile)
} }
db, err := sql.Open("sqlite3", dataFile) db, err := sql.Open("sqlite3", dataFile)
if err != nil { if err != nil {
@ -69,11 +68,16 @@ func MustLoadSQLite(dataFile string) SQLiteStorage {
os.Exit(1) os.Exit(1)
} }
// TODO: Apparently "prepare" works here statement, err := db.Prepare(create)
if _, err := db.Exec(create); err != nil && err.Error() != "table \"users\" already exists" { if err != nil {
slog.Info("error initialising database table", "error", err) if err.Error() != "table \"users\" already exists" {
os.Exit(1) slog.Info("error initialising database table", "error", err)
os.Exit(1)
}
} else {
statement.Exec()
} }
slog.Info("loaded database", "file", dataFile) slog.Info("loaded database", "file", dataFile)
return SQLiteStorage{db} return SQLiteStorage{db}
} }