migrate_data.go 9.1 KB

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