feat: fail on startup if database file does not exist (#8)

Add a check when connecting to the sqlite3 database to ensure that the file
exists before connecting. If the file does not exist, the connection fails.
This commit is contained in:
Hector 2021-02-07 10:36:08 +00:00
parent 188626198f
commit 6355c9e8e1

View File

@ -3,6 +3,7 @@ package db
import ( import (
"database/sql" "database/sql"
"log" "log"
"os"
) )
const queryBadIpsPerJail = "SELECT j.name, (SELECT COUNT(1) FROM bips b WHERE j.name = b.jail) FROM jails j" const queryBadIpsPerJail = "SELECT j.name, (SELECT COUNT(1) FROM bips b WHERE j.name = b.jail) FROM jails j"
@ -14,6 +15,9 @@ type Fail2BanDB struct {
} }
func MustConnectToDb(databasePath string) *Fail2BanDB { func MustConnectToDb(databasePath string) *Fail2BanDB {
if _, err := os.Stat(databasePath); os.IsNotExist(err) {
log.Fatalf("database path does not exist: %v", err)
}
db, err := sql.Open("sqlite3", databasePath) db, err := sql.Open("sqlite3", databasePath)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)