fix(database): keep the dump restore inside its own database file

A SQL dump replay only has to rebuild the tables of the database it
restores into. Run it on a single connection whose attached-database
limit is zero, so the script cannot open or create any other file.
This commit is contained in:
MHSanaei
2026-10-03 13:19:54 +02:00
parent 7d232a76c9
commit d31465e37b
2 changed files with 61 additions and 2 deletions
+27 -2
View File
@@ -9,6 +9,7 @@ import (
"strings"
"unicode/utf8"
"github.com/mattn/go-sqlite3"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
@@ -127,8 +128,7 @@ func RestoreSQLite(dumpPath, dstPath string) error {
return err
}
// mattn/go-sqlite3 executes every statement in a multi-statement string.
if _, err := sqlDB.ExecContext(context.Background(), string(script)); err != nil {
if err := replayDump(sqlDB, string(script)); err != nil {
sqlDB.Close()
os.Remove(dstPath)
return fmt.Errorf("restore failed: %w", err)
@@ -136,6 +136,31 @@ func RestoreSQLite(dumpPath, dstPath string) error {
return sqlDB.Close()
}
// replayDump runs the script on one connection that cannot open a second database
// file: ATTACH and VACUUM INTO both attach, and a dump only rebuilds its own tables.
func replayDump(sqlDB *sql.DB, script string) error {
ctx := context.Background()
conn, err := sqlDB.Conn(ctx)
if err != nil {
return err
}
defer conn.Close()
err = conn.Raw(func(driverConn any) error {
sc, ok := driverConn.(*sqlite3.SQLiteConn)
if !ok {
return fmt.Errorf("unexpected sqlite driver connection %T", driverConn)
}
sc.SetLimit(sqlite3.SQLITE_LIMIT_ATTACHED, 0)
return nil
})
if err != nil {
return err
}
// mattn/go-sqlite3 executes every statement in a multi-statement string.
_, err = conn.ExecContext(ctx, script)
return err
}
// dumpTableData appends one INSERT statement per row of table to b.
func dumpTableData(db *sql.DB, table string, b *strings.Builder) error {
rows, err := db.QueryContext(context.Background(), `SELECT * FROM "`+table+`"`)