@@ -3,6 +3,8 @@ package database_test
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -83,3 +85,37 @@ func TestFirstBoot_PrintsTheAdminPasswordAsABanner(t *testing.T) {
|
||||
t, ok, "the printed password must open the seeded account",
|
||||
)
|
||||
}
|
||||
|
||||
// TestNewDatabase_IsLoggedWithItsPath is the log half of
|
||||
// https://git.eeqj.de/sneak/webhooker/issues/359. A DATA_DIR that is
|
||||
// unexpectedly empty boots exactly like a first start, so the start
|
||||
// that creates the database must say so, and where. Opening that
|
||||
// database again must not.
|
||||
func TestNewDatabase_IsLoggedWithItsPath(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
|
||||
open := func() string {
|
||||
var out bytes.Buffer
|
||||
|
||||
db, err := database.Open(dir, slog.New(slog.NewTextHandler(&out, nil)))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
return out.String()
|
||||
}
|
||||
|
||||
const created = `level=WARN msg="created a new, empty database"`
|
||||
|
||||
first := open()
|
||||
second := open()
|
||||
|
||||
assert.Contains(
|
||||
t, first,
|
||||
created+" path="+filepath.Join(dir, database.MainDBFileName),
|
||||
)
|
||||
assert.NotContains(
|
||||
t, second, created, "an existing database is not new",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -199,6 +200,12 @@ func (d *Database) connectTo(dataDir string) error {
|
||||
// Construct the main application database path inside DATA_DIR.
|
||||
dbPath := filepath.Join(dataDir, MainDBFileName)
|
||||
|
||||
// Checked before opening, which creates the file. A DATA_DIR that
|
||||
// is unexpectedly empty -- its volume not mounted, say -- looks
|
||||
// exactly like a first start, so a new database is a warning.
|
||||
_, statErr := os.Stat(dbPath)
|
||||
created := errors.Is(statErr, fs.ErrNotExist)
|
||||
|
||||
// Opened through OpenSQLite so this handle carries the same WAL
|
||||
// journaling, busy timeout, immediate-transaction locking, and pool
|
||||
// bounds as every other database file. See sqlite_open.go.
|
||||
@@ -229,7 +236,12 @@ func (d *Database) connectTo(dataDir string) error {
|
||||
}
|
||||
|
||||
d.db = db
|
||||
d.log.Info("connected to database", "path", dbPath)
|
||||
|
||||
if created {
|
||||
d.log.Warn("created a new, empty database", "path", dbPath)
|
||||
} else {
|
||||
d.log.Info("connected to database", "path", dbPath)
|
||||
}
|
||||
|
||||
// Run migrations
|
||||
return d.migrate()
|
||||
|
||||
Reference in New Issue
Block a user