Skip to content

Commit 0d6e26a

Browse files
Use memdb for in-memory sqlite dbs.
1 parent e85ca0a commit 0d6e26a

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

config/config.yaml

+4-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ cache:
3232
database:
3333
driver: "sqlite3"
3434
connection: "dbs/main.db?_journal=WAL&_timeout=5000&_fk=true"
35-
testConnection: ":memory:?_journal=WAL&_timeout=5000&_fk=true"
35+
# $RAND will be automatically replaced with a random value.
36+
# memdb is more robust for an in-memory database rather than :memory: because the latter has the potential
37+
# retain data even after you close and re-open the connection.
38+
testConnection: "file:/$RAND?vfs=memdb&_timeout=1000&_fk=true"
3639

3740
files:
3841
directory: "uploads"

pkg/services/container.go

+10-5
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"database/sql"
66
"fmt"
77
"log/slog"
8+
"math/rand"
89
"os"
910
"path"
1011
"path/filepath"
@@ -241,18 +242,22 @@ func (c *Container) initTasks() {
241242

242243
// openDB opens a database connection.
243244
func openDB(driver, connection string) (*sql.DB, error) {
244-
// Helper to automatically create the directories that the specified sqlite file
245-
// should reside in, if one.
246245
if driver == "sqlite3" {
246+
// Helper to automatically create the directories that the specified sqlite file
247+
// should reside in, if one.
247248
d := strings.Split(connection, "/")
248-
249249
if len(d) > 1 {
250-
path := strings.Join(d[:len(d)-1], "/")
250+
dirpath := strings.Join(d[:len(d)-1], "/")
251251

252-
if err := os.MkdirAll(path, 0755); err != nil {
252+
if err := os.MkdirAll(dirpath, 0755); err != nil {
253253
return nil, err
254254
}
255255
}
256+
257+
// Check if a random value is required, which is often used for in-memory test databases.
258+
if strings.Contains(connection, "$RAND") {
259+
connection = strings.Replace(connection, "$RAND", fmt.Sprint(rand.Int()), 1)
260+
}
256261
}
257262

258263
return sql.Open(driver, connection)

0 commit comments

Comments
 (0)