From 82aba0c9e921fe9adef186d33475a58f0eee3213 Mon Sep 17 00:00:00 2001 From: Andrew-71 Date: Sat, 12 Oct 2024 21:58:42 +0300 Subject: [PATCH] Add SQLite file creation --- .gitignore | 3 ++- storage/sqlite/sqlite.go | 18 +++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index c5e0910..efd9b43 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ pye private.key -dev-data.db \ No newline at end of file +dev-data.db +data.db \ No newline at end of file diff --git a/storage/sqlite/sqlite.go b/storage/sqlite/sqlite.go index 1a835d4..98926d7 100644 --- a/storage/sqlite/sqlite.go +++ b/storage/sqlite/sqlite.go @@ -58,10 +58,9 @@ func (s SQLiteStorage) EmailExists(email string) bool { } 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) { - slog.Error("sqlite3 database file required", "file", dataFile) - os.Exit(1) + os.Create(dataFile) + slog.Info("created sqlite3 database file", "file", dataFile) } db, err := sql.Open("sqlite3", dataFile) if err != nil { @@ -69,11 +68,16 @@ func MustLoadSQLite(dataFile string) SQLiteStorage { os.Exit(1) } - // TODO: Apparently "prepare" works here - if _, err := db.Exec(create); err != nil && err.Error() != "table \"users\" already exists" { - slog.Info("error initialising database table", "error", err) - os.Exit(1) + statement, err := db.Prepare(create) + if err != nil { + if err.Error() != "table \"users\" already exists" { + slog.Info("error initialising database table", "error", err) + os.Exit(1) + } + } else { + statement.Exec() } + slog.Info("loaded database", "file", dataFile) return SQLiteStorage{db} }