1
0

migrate_data.go 4.9 KB

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