migrate_data.go 11 KB

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