1
0

migrate_data.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. package database
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "os"
  8. "path"
  9. "reflect"
  10. "strings"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. "gorm.io/driver/postgres"
  15. "gorm.io/driver/sqlite"
  16. "gorm.io/gorm"
  17. "gorm.io/gorm/logger"
  18. )
  19. // migrationModels is the FK-aware order in which tables are created and copied
  20. // during `x-ui migrate-db --dsn` (SQLite → PostgreSQL data migration) and in
  21. // related tests.
  22. //
  23. // Important: When adding a new top-level model (like OutboundSubscription),
  24. // you must add it here **in addition to** allModels() in internal/database/db.go;
  25. // TestMigrationModelsMatchPanelModels fails when the two lists drift apart.
  26. // This list is used for:
  27. // - Creating the destination schema during cross-DB migration
  28. // - Truncating tables
  29. // - Copying data row-by-row
  30. // - Resyncing Postgres sequences after bulk insert
  31. //
  32. // DumpSQLite / RestoreSQLite are schema-introspective (they read sqlite_master)
  33. // so they do not need manual updates.
  34. func migrationModels() []any {
  35. return []any{
  36. &model.User{},
  37. &model.Setting{},
  38. &model.HistoryOfSeeders{},
  39. &model.Node{},
  40. &model.ApiToken{},
  41. &model.Inbound{},
  42. &xray.ClientTraffic{},
  43. &model.OutboundTraffics{},
  44. &model.InboundClientIps{},
  45. &model.ClientRecord{},
  46. &model.ClientInbound{},
  47. &model.ClientHwid{},
  48. &model.ClientExternalLink{},
  49. &model.ClientGroup{},
  50. &model.InboundFallback{},
  51. &model.Host{},
  52. &model.NodeClientTraffic{},
  53. &model.NodeClientIp{},
  54. &model.ClientGlobalTraffic{},
  55. &model.NodePendingReset{},
  56. &model.OutboundSubscription{},
  57. &model.SubBalancer{},
  58. &model.TuicTrafficReceipt{},
  59. }
  60. }
  61. // MigrateData copies every row from the configured SQLite file at srcPath into
  62. // a fresh PostgreSQL database described by dstDSN. The destination tables are
  63. // (re)created with AutoMigrate; truncate and copy then run in one transaction,
  64. // so a failed migration leaves the destination data unchanged. Source data is
  65. // left untouched.
  66. func MigrateData(srcPath, dstDSN string) error {
  67. if _, err := os.Stat(srcPath); err != nil {
  68. return fmt.Errorf("source sqlite not found at %s: %w", srcPath, err)
  69. }
  70. if dstDSN == "" {
  71. return errors.New("destination DSN is required")
  72. }
  73. if err := os.MkdirAll(path.Dir(srcPath), 0o755); err != nil {
  74. return err
  75. }
  76. srcDSN := srcPath + "?_journal_mode=WAL&_busy_timeout=10000"
  77. src, err := gorm.Open(sqlite.Open(srcDSN), &gorm.Config{Logger: logger.Discard})
  78. if err != nil {
  79. return fmt.Errorf("open sqlite source: %w", err)
  80. }
  81. srcSQL, err := src.DB()
  82. if err != nil {
  83. return err
  84. }
  85. defer srcSQL.Close()
  86. dst, err := gorm.Open(postgres.Open(dstDSN), &gorm.Config{Logger: logger.Discard})
  87. if err != nil {
  88. return fmt.Errorf("open postgres destination: %w", err)
  89. }
  90. dstSQL, err := dst.DB()
  91. if err != nil {
  92. return err
  93. }
  94. defer dstSQL.Close()
  95. dstSQL.SetConnMaxLifetime(time.Hour)
  96. log.Println("Creating destination schema...")
  97. for _, m := range migrationModels() {
  98. if err := dst.AutoMigrate(m); err != nil {
  99. return fmt.Errorf("AutoMigrate %T: %w", m, err)
  100. }
  101. }
  102. totalRows := 0
  103. txErr := dst.Transaction(func(tx *gorm.DB) error {
  104. // AutoMigrate re-creates the legacy client_traffics -> inbounds foreign key,
  105. // but the running panel drops it (see dropLegacyForeignKeys) and tolerates
  106. // client_traffics rows whose inbound was deleted. Drop it here too so copying
  107. // such orphaned rows can't fail with an fk_inbounds_client_stats violation.
  108. if err := tx.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  109. return fmt.Errorf("drop legacy foreign key: %w", err)
  110. }
  111. // Empty the destination tables before copying: a fresh PostgreSQL DB
  112. // already holds an auto-seeded admin (id=1) from any prior panel start,
  113. // so a plain INSERT with explicit ids would collide on users_pkey. Only
  114. // the panel's own tables are cleared, and a failure anywhere in this
  115. // transaction rolls the clear back with everything else.
  116. if err := truncatePostgresTables(tx, migrationModels()); err != nil {
  117. return fmt.Errorf("clear destination tables: %w", err)
  118. }
  119. for _, m := range migrationModels() {
  120. n, err := copyTable(src, tx, m)
  121. if err != nil {
  122. return fmt.Errorf("copy %T: %w", m, err)
  123. }
  124. totalRows += n
  125. log.Printf(" %-32s %d rows", reflect.TypeOf(m).Elem().Name(), n)
  126. }
  127. return nil
  128. })
  129. if txErr != nil {
  130. return txErr
  131. }
  132. // setval is never rolled back by PostgreSQL, so sequences are resynced only
  133. // after the transaction has committed.
  134. if err := resetPostgresSequences(dst); err != nil {
  135. log.Printf("warning: failed to reset some postgres sequences: %v", err)
  136. }
  137. log.Printf("Migration complete: %d rows across %d tables.", totalRows, len(migrationModels()))
  138. log.Println("Set XUI_DB_TYPE=postgres and XUI_DB_DSN=... in /etc/default/x-ui, then restart x-ui.")
  139. return nil
  140. }
  141. // ExportPostgresToSQLite copies every row from the PostgreSQL database described
  142. // by srcDSN into a fresh SQLite file at dstPath. It is the reverse of
  143. // MigrateData and is used to hand a PostgreSQL-backed panel a portable .db file.
  144. // dstPath is created/overwritten; the PostgreSQL source is left untouched.
  145. func ExportPostgresToSQLite(srcDSN, dstPath string) error {
  146. if srcDSN == "" {
  147. return errors.New("source DSN is required")
  148. }
  149. if err := os.MkdirAll(path.Dir(dstPath), 0o755); err != nil {
  150. return err
  151. }
  152. // Start from an empty file so AutoMigrate creates the canonical schema.
  153. if err := os.Remove(dstPath); err != nil && !os.IsNotExist(err) {
  154. return err
  155. }
  156. src, err := gorm.Open(postgres.Open(srcDSN), &gorm.Config{Logger: logger.Discard})
  157. if err != nil {
  158. return fmt.Errorf("open postgres source: %w", err)
  159. }
  160. srcSQL, err := src.DB()
  161. if err != nil {
  162. return err
  163. }
  164. defer srcSQL.Close()
  165. // No WAL: keep all data in the main file so it is complete once closed.
  166. dst, err := gorm.Open(sqlite.Open(dstPath+"?_busy_timeout=10000"), &gorm.Config{Logger: logger.Discard})
  167. if err != nil {
  168. return fmt.Errorf("open sqlite destination: %w", err)
  169. }
  170. dstSQL, err := dst.DB()
  171. if err != nil {
  172. return err
  173. }
  174. defer dstSQL.Close()
  175. return copyAllModels(src, dst)
  176. }
  177. // copyAllModels (re)creates the schema on dst and copies every migrated table
  178. // from src to dst in FK-safe order. src/dst may be any gorm backend.
  179. func copyAllModels(src, dst *gorm.DB) error {
  180. for _, m := range migrationModels() {
  181. if err := dst.AutoMigrate(m); err != nil {
  182. return fmt.Errorf("AutoMigrate %T: %w", m, err)
  183. }
  184. }
  185. for _, m := range migrationModels() {
  186. if _, err := copyTable(src, dst, m); err != nil {
  187. return fmt.Errorf("copy %T: %w", m, err)
  188. }
  189. }
  190. return nil
  191. }
  192. func copyTable(src, dst *gorm.DB, mdl any) (int, error) {
  193. const batchSize = 500
  194. sliceType := reflect.SliceOf(reflect.PointerTo(reflect.TypeOf(mdl).Elem()))
  195. stmt := &gorm.Statement{DB: src}
  196. if err := stmt.Parse(mdl); err != nil {
  197. return 0, err
  198. }
  199. order := strings.Join(stmt.Schema.PrimaryFieldDBNames, ", ")
  200. table := stmt.Schema.Table
  201. columns := stmt.Schema.DBNames
  202. ctx := context.Background()
  203. total := 0
  204. for offset := 0; ; offset += batchSize {
  205. batchPtr := reflect.New(sliceType)
  206. q := src.Model(mdl).Limit(batchSize).Offset(offset)
  207. if order != "" {
  208. q = q.Order(order)
  209. }
  210. if err := q.Find(batchPtr.Interface()).Error; err != nil {
  211. return total, err
  212. }
  213. slice := batchPtr.Elem()
  214. n := slice.Len()
  215. if n == 0 {
  216. break
  217. }
  218. rows := make([]map[string]any, n)
  219. for i := range n {
  220. rv := reflect.Indirect(slice.Index(i))
  221. row := make(map[string]any, len(columns))
  222. for _, name := range columns {
  223. value, _ := stmt.Schema.FieldsByDBName[name].ValueOf(ctx, rv)
  224. row[name] = value
  225. }
  226. rows[i] = row
  227. }
  228. if err := dst.Table(table).CreateInBatches(rows, 200).Error; err != nil {
  229. return total, err
  230. }
  231. total += n
  232. if n < batchSize {
  233. break
  234. }
  235. }
  236. return total, nil
  237. }
  238. // truncatePostgresTables empties every migrated table on dst in a single
  239. // statement, resetting identity sequences. CASCADE covers the inbound/client
  240. // foreign keys regardless of insertion order. Only the panel's own tables are
  241. // touched, never the rest of the schema.
  242. func truncatePostgresTables(dst *gorm.DB, models []any) error {
  243. tables := make([]string, 0, len(models))
  244. for _, m := range models {
  245. stmt := &gorm.Statement{DB: dst}
  246. if err := stmt.Parse(m); err != nil {
  247. return err
  248. }
  249. tables = append(tables, `"`+stmt.Schema.Table+`"`)
  250. }
  251. if len(tables) == 0 {
  252. return nil
  253. }
  254. log.Println("Clearing destination tables...")
  255. return dst.Exec("TRUNCATE TABLE " + strings.Join(tables, ", ") + " RESTART IDENTITY CASCADE").Error
  256. }
  257. // resetPostgresSequences advances each migrated table's id sequence past MAX(id),
  258. // otherwise the next INSERT-without-id would clash with copied rows.
  259. func resetPostgresSequences(dst *gorm.DB) error {
  260. return resyncPostgresSequences(dst, migrationModels())
  261. }
  262. // resyncPostgresSequences sets each model's id sequence to MAX(id); idempotent. Id-less
  263. // composite-PK tables are skipped — Postgres rejects MAX(id) at parse time and logs it (#5665).
  264. func resyncPostgresSequences(db *gorm.DB, models []any) error {
  265. for _, m := range models {
  266. t, ok := tableWithIdColumn(db, m)
  267. if !ok {
  268. continue
  269. }
  270. // t comes from the trusted model set parsed by GORM, not user input, so
  271. // interpolating it as an identifier is safe. We ignore errors per-table.
  272. _ = db.Exec(
  273. `SELECT setval(pg_get_serial_sequence(?, 'id'), COALESCE((SELECT MAX(id) FROM "`+t+`"), 1), true)
  274. WHERE pg_get_serial_sequence(?, 'id') IS NOT NULL`,
  275. t, t,
  276. ).Error
  277. }
  278. return nil
  279. }
  280. // tableWithIdColumn resolves a model's table name and reports whether its GORM
  281. // schema maps an "id" database column.
  282. func tableWithIdColumn(db *gorm.DB, m any) (string, bool) {
  283. stmt := &gorm.Statement{DB: db}
  284. if err := stmt.Parse(m); err != nil {
  285. return "", false
  286. }
  287. if stmt.Schema == nil || stmt.Schema.LookUpField("id") == nil {
  288. return "", false
  289. }
  290. return stmt.Table, true
  291. }
  292. // PrepareSQLiteForMigration rejects SQLite files that are not a panel database
  293. // before the caller causes any downtime, then AutoMigrates the panel schema
  294. // onto the file so backups from older versions gain the newer tables and
  295. // columns the row copy reads. Data-level upgrades are not needed here: they
  296. // run dialect-agnostically on the destination via InitDB after the import.
  297. func PrepareSQLiteForMigration(dbPath string) error {
  298. gdb, err := gorm.Open(sqlite.Open(dbPath+"?_busy_timeout=10000"), &gorm.Config{Logger: logger.Discard})
  299. if err != nil {
  300. return err
  301. }
  302. sqlDB, err := gdb.DB()
  303. if err != nil {
  304. return err
  305. }
  306. defer sqlDB.Close()
  307. for _, table := range []string{"users", "settings", "inbounds"} {
  308. if !sqliteTableExists(sqlDB, table) {
  309. return fmt.Errorf("not a 3x-ui panel database: required table %q is missing", table)
  310. }
  311. }
  312. for _, m := range migrationModels() {
  313. if err := gdb.AutoMigrate(m); err != nil && !isIgnorableDuplicateColumnErr(gdb, err, m) {
  314. return fmt.Errorf("upgrade panel schema for %T: %w", m, err)
  315. }
  316. }
  317. return nil
  318. }