migrate_data.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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/database/model"
  13. "github.com/mhsanaei/3x-ui/v3/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. // Parents come before their children so foreign-key constraints stay satisfied
  21. // even when checks are not explicitly disabled.
  22. func migrationModels() []any {
  23. return []any{
  24. &model.User{},
  25. &model.Setting{},
  26. &model.HistoryOfSeeders{},
  27. &model.CustomGeoResource{},
  28. &model.Node{},
  29. &model.ApiToken{},
  30. &model.Inbound{},
  31. &xray.ClientTraffic{},
  32. &model.OutboundTraffics{},
  33. &model.InboundClientIps{},
  34. &model.ClientRecord{},
  35. &model.ClientInbound{},
  36. &model.InboundFallback{},
  37. &model.NodeClientTraffic{},
  38. }
  39. }
  40. // MigrateData copies every row from the configured SQLite file at srcPath into
  41. // a fresh PostgreSQL database described by dstDSN. The destination tables are
  42. // (re)created with AutoMigrate before the copy. Source data is left untouched.
  43. func MigrateData(srcPath, dstDSN string) error {
  44. if _, err := os.Stat(srcPath); err != nil {
  45. return fmt.Errorf("source sqlite not found at %s: %w", srcPath, err)
  46. }
  47. if dstDSN == "" {
  48. return errors.New("destination DSN is required")
  49. }
  50. if err := os.MkdirAll(path.Dir(srcPath), 0755); err != nil {
  51. return err
  52. }
  53. srcDSN := srcPath + "?_journal_mode=WAL&_busy_timeout=10000"
  54. src, err := gorm.Open(sqlite.Open(srcDSN), &gorm.Config{Logger: logger.Discard})
  55. if err != nil {
  56. return fmt.Errorf("open sqlite source: %w", err)
  57. }
  58. srcSQL, err := src.DB()
  59. if err != nil {
  60. return err
  61. }
  62. defer srcSQL.Close()
  63. dst, err := gorm.Open(postgres.Open(dstDSN), &gorm.Config{Logger: logger.Discard})
  64. if err != nil {
  65. return fmt.Errorf("open postgres destination: %w", err)
  66. }
  67. dstSQL, err := dst.DB()
  68. if err != nil {
  69. return err
  70. }
  71. defer dstSQL.Close()
  72. dstSQL.SetConnMaxLifetime(time.Hour)
  73. log.Println("Creating destination schema...")
  74. for _, m := range migrationModels() {
  75. if err := dst.AutoMigrate(m); err != nil {
  76. return fmt.Errorf("AutoMigrate %T: %w", m, err)
  77. }
  78. }
  79. // Empty the destination tables so the migration is idempotent: a fresh
  80. // PostgreSQL DB already holds an auto-seeded admin (id=1) from any prior
  81. // panel start, and a partially-failed earlier run leaves rows behind. Either
  82. // way a plain INSERT with explicit ids would collide on users_pkey, so clear
  83. // our tables (only) before copying.
  84. if err := truncatePostgresTables(dst, migrationModels()); err != nil {
  85. return fmt.Errorf("clear destination tables: %w", err)
  86. }
  87. totalRows := 0
  88. for _, m := range migrationModels() {
  89. n, err := copyTable(src, dst, m)
  90. if err != nil {
  91. return fmt.Errorf("copy %T: %w", m, err)
  92. }
  93. totalRows += n
  94. log.Printf(" %-32s %d rows", reflect.TypeOf(m).Elem().Name(), n)
  95. }
  96. if err := resetPostgresSequences(dst); err != nil {
  97. log.Printf("warning: failed to reset some postgres sequences: %v", err)
  98. }
  99. log.Printf("Migration complete: %d rows across %d tables.", totalRows, len(migrationModels()))
  100. log.Println("Set XUI_DB_TYPE=postgres and XUI_DB_DSN=... in /etc/default/x-ui, then restart x-ui.")
  101. return nil
  102. }
  103. // ExportPostgresToSQLite copies every row from the PostgreSQL database described
  104. // by srcDSN into a fresh SQLite file at dstPath. It is the reverse of
  105. // MigrateData and is used to hand a PostgreSQL-backed panel a portable .db file.
  106. // dstPath is created/overwritten; the PostgreSQL source is left untouched.
  107. func ExportPostgresToSQLite(srcDSN, dstPath string) error {
  108. if srcDSN == "" {
  109. return errors.New("source DSN is required")
  110. }
  111. if err := os.MkdirAll(path.Dir(dstPath), 0755); err != nil {
  112. return err
  113. }
  114. // Start from an empty file so AutoMigrate creates the canonical schema.
  115. if err := os.Remove(dstPath); err != nil && !os.IsNotExist(err) {
  116. return err
  117. }
  118. src, err := gorm.Open(postgres.Open(srcDSN), &gorm.Config{Logger: logger.Discard})
  119. if err != nil {
  120. return fmt.Errorf("open postgres source: %w", err)
  121. }
  122. srcSQL, err := src.DB()
  123. if err != nil {
  124. return err
  125. }
  126. defer srcSQL.Close()
  127. // No WAL: keep all data in the main file so it is complete once closed.
  128. dst, err := gorm.Open(sqlite.Open(dstPath+"?_busy_timeout=10000"), &gorm.Config{Logger: logger.Discard})
  129. if err != nil {
  130. return fmt.Errorf("open sqlite destination: %w", err)
  131. }
  132. dstSQL, err := dst.DB()
  133. if err != nil {
  134. return err
  135. }
  136. defer dstSQL.Close()
  137. return copyAllModels(src, dst)
  138. }
  139. // copyAllModels (re)creates the schema on dst and copies every migrated table
  140. // from src to dst in FK-safe order. src/dst may be any gorm backend.
  141. func copyAllModels(src, dst *gorm.DB) error {
  142. for _, m := range migrationModels() {
  143. if err := dst.AutoMigrate(m); err != nil {
  144. return fmt.Errorf("AutoMigrate %T: %w", m, err)
  145. }
  146. }
  147. for _, m := range migrationModels() {
  148. if _, err := copyTable(src, dst, m); err != nil {
  149. return fmt.Errorf("copy %T: %w", m, err)
  150. }
  151. }
  152. return nil
  153. }
  154. func copyTable(src, dst *gorm.DB, mdl any) (int, error) {
  155. const batchSize = 500
  156. sliceType := reflect.SliceOf(reflect.PointerTo(reflect.TypeOf(mdl).Elem()))
  157. stmt := &gorm.Statement{DB: src}
  158. if err := stmt.Parse(mdl); err != nil {
  159. return 0, err
  160. }
  161. order := strings.Join(stmt.Schema.PrimaryFieldDBNames, ", ")
  162. table := stmt.Schema.Table
  163. columns := stmt.Schema.DBNames
  164. ctx := context.Background()
  165. total := 0
  166. for offset := 0; ; offset += batchSize {
  167. batchPtr := reflect.New(sliceType)
  168. q := src.Model(mdl).Limit(batchSize).Offset(offset)
  169. if order != "" {
  170. q = q.Order(order)
  171. }
  172. if err := q.Find(batchPtr.Interface()).Error; err != nil {
  173. return total, err
  174. }
  175. slice := batchPtr.Elem()
  176. n := slice.Len()
  177. if n == 0 {
  178. break
  179. }
  180. rows := make([]map[string]any, n)
  181. for i := 0; i < n; i++ {
  182. rv := reflect.Indirect(slice.Index(i))
  183. row := make(map[string]any, len(columns))
  184. for _, name := range columns {
  185. value, _ := stmt.Schema.FieldsByDBName[name].ValueOf(ctx, rv)
  186. row[name] = value
  187. }
  188. rows[i] = row
  189. }
  190. if err := dst.Table(table).CreateInBatches(rows, 200).Error; err != nil {
  191. return total, err
  192. }
  193. total += n
  194. if n < batchSize {
  195. break
  196. }
  197. }
  198. return total, nil
  199. }
  200. // truncatePostgresTables empties every migrated table on dst in a single
  201. // statement, resetting identity sequences. CASCADE covers the inbound/client
  202. // foreign keys regardless of insertion order. Only the panel's own tables are
  203. // touched, never the rest of the schema.
  204. func truncatePostgresTables(dst *gorm.DB, models []any) error {
  205. tables := make([]string, 0, len(models))
  206. for _, m := range models {
  207. stmt := &gorm.Statement{DB: dst}
  208. if err := stmt.Parse(m); err != nil {
  209. return err
  210. }
  211. tables = append(tables, `"`+stmt.Schema.Table+`"`)
  212. }
  213. if len(tables) == 0 {
  214. return nil
  215. }
  216. log.Println("Clearing destination tables...")
  217. return dst.Exec("TRUNCATE TABLE " + strings.Join(tables, ", ") + " RESTART IDENTITY CASCADE").Error
  218. }
  219. // resetPostgresSequences advances each migrated table's id sequence past MAX(id),
  220. // otherwise the next INSERT-without-id would clash with copied rows.
  221. func resetPostgresSequences(dst *gorm.DB) error {
  222. return resyncPostgresSequences(dst, migrationModels())
  223. }
  224. // resyncPostgresSequences sets each model's id sequence to MAX(id) so the next
  225. // auto-increment INSERT won't collide with an existing row. Table names are
  226. // resolved from the models themselves (not hardcoded), so they always match the
  227. // migrated tables. The statement is a no-op for tables without an id sequence
  228. // (e.g. composite-PK tables), and idempotent on a healthy DB, so it is safe to
  229. // run both after migration and on every Postgres startup.
  230. func resyncPostgresSequences(db *gorm.DB, models []any) error {
  231. for _, m := range models {
  232. stmt := &gorm.Statement{DB: db}
  233. if err := stmt.Parse(m); err != nil {
  234. continue
  235. }
  236. t := stmt.Table
  237. // t comes from the trusted model set parsed by GORM, not user input, so
  238. // interpolating it as an identifier is safe. We ignore errors per-table.
  239. _ = db.Exec(
  240. `SELECT setval(pg_get_serial_sequence(?, 'id'), COALESCE((SELECT MAX(id) FROM "`+t+`"), 1), true)
  241. WHERE pg_get_serial_sequence(?, 'id') IS NOT NULL`,
  242. t, t,
  243. ).Error
  244. }
  245. return nil
  246. }