1
0

migrate_data.go 9.1 KB

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