mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-10-04 21:22:07 +03:00
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:
@@ -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+`"`)
|
||||
|
||||
Reference in New Issue
Block a user