fix(sqlite): enable WAL and export consistent snapshots

This commit is contained in:
Noru Wyrms
2026-10-25 02:27:05 +00:00
parent 02a2b79c08
commit ada0550571
7 changed files with 185 additions and 5 deletions
+17
View File
@@ -6,6 +6,7 @@ package db
import (
"context"
"fmt"
"log"
"net"
"net/url"
@@ -58,6 +59,10 @@ func initSQLite() {
log.Fatalf("[SQLite] init connection failed: %v\n", err)
}
if err = enableSQLiteWAL(db); err != nil {
log.Fatalf("[SQLite] enable WAL failed: %v\n", err)
}
// Trace 注入
if err = db.Use(
newGORMTracingPlugin([]attribute.KeyValue{
@@ -71,6 +76,18 @@ func initSQLite() {
log.Printf("[SQLite] initialized (path: %s)\n", sqlitePath)
}
// enableSQLiteWAL 在文件数据库上启用 WAL;内存数据库仅支持 memory 日志模式。
func enableSQLiteWAL(database *gorm.DB) error {
var mode string
if err := database.Raw("PRAGMA journal_mode = WAL").Scan(&mode).Error; err != nil {
return err
}
if mode != "wal" && mode != "memory" {
return fmt.Errorf("unexpected SQLite journal mode: %s", mode)
}
return nil
}
// initPostgres 初始化 PostgreSQL 数据库
func initPostgres() {
var err error
+48
View File
@@ -0,0 +1,48 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package db
import (
"path/filepath"
"testing"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func TestEnableSQLiteWAL(t *testing.T) {
for _, tc := range []struct{ name, path, mode string }{
{"file", filepath.Join(t.TempDir(), "database.db"), "wal"},
{"memory", ":memory:", "memory"},
} {
t.Run(tc.name, func(t *testing.T) {
database, err := gorm.Open(sqlite.Open(tc.path), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
sqlDB, err := database.DB()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := sqlDB.Close(); err != nil {
t.Error(err)
}
})
if err := enableSQLiteWAL(database); err != nil {
t.Fatal(err)
}
var mode string
if err := database.Raw("PRAGMA journal_mode").Scan(&mode).Error; err != nil {
t.Fatal(err)
}
if mode != tc.mode {
t.Fatalf("journal mode = %q, want %q", mode, tc.mode)
}
if err := enableSQLiteWAL(database); err != nil {
t.Fatalf("enable WAL again: %v", err)
}
})
}
}