1
0

migrate_data.go 11 KB

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