migrate_data.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. package database
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "os"
  7. "path"
  8. "reflect"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/xray"
  12. "gorm.io/driver/postgres"
  13. "gorm.io/driver/sqlite"
  14. "gorm.io/gorm"
  15. "gorm.io/gorm/logger"
  16. )
  17. // migrationModels is the FK-aware order in which tables are created and copied.
  18. // Parents come before their children so foreign-key constraints stay satisfied
  19. // even when checks are not explicitly disabled.
  20. func migrationModels() []any {
  21. return []any{
  22. &model.User{},
  23. &model.Setting{},
  24. &model.HistoryOfSeeders{},
  25. &model.CustomGeoResource{},
  26. &model.Node{},
  27. &model.ApiToken{},
  28. &model.Inbound{},
  29. &xray.ClientTraffic{},
  30. &model.OutboundTraffics{},
  31. &model.InboundClientIps{},
  32. &model.ClientRecord{},
  33. &model.ClientInbound{},
  34. &model.InboundFallback{},
  35. &model.NodeClientTraffic{},
  36. }
  37. }
  38. // MigrateData copies every row from the configured SQLite file at srcPath into
  39. // a fresh PostgreSQL database described by dstDSN. The destination tables are
  40. // (re)created with AutoMigrate before the copy. Source data is left untouched.
  41. func MigrateData(srcPath, dstDSN string) error {
  42. if _, err := os.Stat(srcPath); err != nil {
  43. return fmt.Errorf("source sqlite not found at %s: %w", srcPath, err)
  44. }
  45. if dstDSN == "" {
  46. return errors.New("destination DSN is required")
  47. }
  48. if err := os.MkdirAll(path.Dir(srcPath), 0755); err != nil {
  49. return err
  50. }
  51. srcDSN := srcPath + "?_journal_mode=WAL&_busy_timeout=10000"
  52. src, err := gorm.Open(sqlite.Open(srcDSN), &gorm.Config{Logger: logger.Discard})
  53. if err != nil {
  54. return fmt.Errorf("open sqlite source: %w", err)
  55. }
  56. srcSQL, err := src.DB()
  57. if err != nil {
  58. return err
  59. }
  60. defer srcSQL.Close()
  61. dst, err := gorm.Open(postgres.Open(dstDSN), &gorm.Config{Logger: logger.Discard})
  62. if err != nil {
  63. return fmt.Errorf("open postgres destination: %w", err)
  64. }
  65. dstSQL, err := dst.DB()
  66. if err != nil {
  67. return err
  68. }
  69. defer dstSQL.Close()
  70. dstSQL.SetConnMaxLifetime(time.Hour)
  71. log.Println("Creating destination schema...")
  72. for _, m := range migrationModels() {
  73. if err := dst.AutoMigrate(m); err != nil {
  74. return fmt.Errorf("AutoMigrate %T: %w", m, err)
  75. }
  76. }
  77. totalRows := 0
  78. for _, m := range migrationModels() {
  79. n, err := copyTable(src, dst, m)
  80. if err != nil {
  81. return fmt.Errorf("copy %T: %w", m, err)
  82. }
  83. totalRows += n
  84. log.Printf(" %-32s %d rows", reflect.TypeOf(m).Elem().Name(), n)
  85. }
  86. if err := resetPostgresSequences(dst); err != nil {
  87. log.Printf("warning: failed to reset some postgres sequences: %v", err)
  88. }
  89. log.Printf("Migration complete: %d rows across %d tables.", totalRows, len(migrationModels()))
  90. log.Println("Set XUI_DB_TYPE=postgres and XUI_DB_DSN=... in /etc/default/x-ui, then restart x-ui.")
  91. return nil
  92. }
  93. // copyTable streams every row of `mdl` from src to dst in batches.
  94. func copyTable(src, dst *gorm.DB, mdl any) (int, error) {
  95. sliceType := reflect.SliceOf(reflect.PointerTo(reflect.TypeOf(mdl).Elem()))
  96. batchPtr := reflect.New(sliceType)
  97. batchPtr.Elem().Set(reflect.MakeSlice(sliceType, 0, 0))
  98. total := 0
  99. err := src.Model(mdl).FindInBatches(batchPtr.Interface(), 500, func(tx *gorm.DB, _ int) error {
  100. batch := batchPtr.Elem()
  101. if batch.Len() == 0 {
  102. return nil
  103. }
  104. if err := dst.CreateInBatches(batchPtr.Interface(), 200).Error; err != nil {
  105. return err
  106. }
  107. total += batch.Len()
  108. return nil
  109. }).Error
  110. return total, err
  111. }
  112. // resetPostgresSequences advances each migrated table's id sequence past MAX(id),
  113. // otherwise the next INSERT-without-id would clash with copied rows.
  114. func resetPostgresSequences(dst *gorm.DB) error {
  115. return resyncPostgresSequences(dst, migrationModels())
  116. }
  117. // resyncPostgresSequences sets each model's id sequence to MAX(id) so the next
  118. // auto-increment INSERT won't collide with an existing row. Table names are
  119. // resolved from the models themselves (not hardcoded), so they always match the
  120. // migrated tables. The statement is a no-op for tables without an id sequence
  121. // (e.g. composite-PK tables), and idempotent on a healthy DB, so it is safe to
  122. // run both after migration and on every Postgres startup.
  123. func resyncPostgresSequences(db *gorm.DB, models []any) error {
  124. for _, m := range models {
  125. stmt := &gorm.Statement{DB: db}
  126. if err := stmt.Parse(m); err != nil {
  127. continue
  128. }
  129. t := stmt.Table
  130. // t comes from the trusted model set parsed by GORM, not user input, so
  131. // interpolating it as an identifier is safe. We ignore errors per-table.
  132. _ = db.Exec(
  133. `SELECT setval(pg_get_serial_sequence(?, 'id'), COALESCE((SELECT MAX(id) FROM "`+t+`"), 1), true)
  134. WHERE pg_get_serial_sequence(?, 'id') IS NOT NULL`,
  135. t, t,
  136. ).Error
  137. }
  138. return nil
  139. }