migrate_data.go 9.1 KB

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