migrate_data.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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** allModels() in internal/database/db.go;
  25. // TestMigrationModelsMatchPanelModels fails when the two lists drift apart.
  26. // This list is used for:
  27. // - Creating the destination schema during cross-DB migration
  28. // - Truncating tables
  29. // - Copying data row-by-row
  30. // - Resyncing Postgres sequences after bulk insert
  31. //
  32. // DumpSQLite / RestoreSQLite are schema-introspective (they read sqlite_master)
  33. // so they do not need manual updates.
  34. func migrationModels() []any {
  35. return []any{
  36. &model.User{},
  37. &model.Setting{},
  38. &model.HistoryOfSeeders{},
  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.ClientHwid{},
  48. &model.ClientExternalLink{},
  49. &model.ClientGroup{},
  50. &model.InboundFallback{},
  51. &model.Host{},
  52. &model.NodeClientTraffic{},
  53. &model.NodeClientIp{},
  54. &model.ClientGlobalTraffic{},
  55. &model.OutboundSubscription{},
  56. &model.SubBalancer{},
  57. }
  58. }
  59. // MigrateData copies every row from the configured SQLite file at srcPath into
  60. // a fresh PostgreSQL database described by dstDSN. The destination tables are
  61. // (re)created with AutoMigrate; truncate and copy then run in one transaction,
  62. // so a failed migration leaves the destination data unchanged. Source data is
  63. // left untouched.
  64. func MigrateData(srcPath, dstDSN string) error {
  65. if _, err := os.Stat(srcPath); err != nil {
  66. return fmt.Errorf("source sqlite not found at %s: %w", srcPath, err)
  67. }
  68. if dstDSN == "" {
  69. return errors.New("destination DSN is required")
  70. }
  71. if err := os.MkdirAll(path.Dir(srcPath), 0o755); err != nil {
  72. return err
  73. }
  74. srcDSN := srcPath + "?_journal_mode=WAL&_busy_timeout=10000"
  75. src, err := gorm.Open(sqlite.Open(srcDSN), &gorm.Config{Logger: logger.Discard})
  76. if err != nil {
  77. return fmt.Errorf("open sqlite source: %w", err)
  78. }
  79. srcSQL, err := src.DB()
  80. if err != nil {
  81. return err
  82. }
  83. defer srcSQL.Close()
  84. dst, err := gorm.Open(postgres.Open(dstDSN), &gorm.Config{Logger: logger.Discard})
  85. if err != nil {
  86. return fmt.Errorf("open postgres destination: %w", err)
  87. }
  88. dstSQL, err := dst.DB()
  89. if err != nil {
  90. return err
  91. }
  92. defer dstSQL.Close()
  93. dstSQL.SetConnMaxLifetime(time.Hour)
  94. log.Println("Creating destination schema...")
  95. for _, m := range migrationModels() {
  96. if err := dst.AutoMigrate(m); err != nil {
  97. return fmt.Errorf("AutoMigrate %T: %w", m, err)
  98. }
  99. }
  100. totalRows := 0
  101. txErr := dst.Transaction(func(tx *gorm.DB) error {
  102. // AutoMigrate re-creates the legacy client_traffics -> inbounds foreign key,
  103. // but the running panel drops it (see dropLegacyForeignKeys) and tolerates
  104. // client_traffics rows whose inbound was deleted. Drop it here too so copying
  105. // such orphaned rows can't fail with an fk_inbounds_client_stats violation.
  106. if err := tx.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  107. return fmt.Errorf("drop legacy foreign key: %w", err)
  108. }
  109. // Empty the destination tables before copying: a fresh PostgreSQL DB
  110. // already holds an auto-seeded admin (id=1) from any prior panel start,
  111. // so a plain INSERT with explicit ids would collide on users_pkey. Only
  112. // the panel's own tables are cleared, and a failure anywhere in this
  113. // transaction rolls the clear back with everything else.
  114. if err := truncatePostgresTables(tx, migrationModels()); err != nil {
  115. return fmt.Errorf("clear destination tables: %w", err)
  116. }
  117. for _, m := range migrationModels() {
  118. n, err := copyTable(src, tx, m)
  119. if err != nil {
  120. return fmt.Errorf("copy %T: %w", m, err)
  121. }
  122. totalRows += n
  123. log.Printf(" %-32s %d rows", reflect.TypeOf(m).Elem().Name(), n)
  124. }
  125. return nil
  126. })
  127. if txErr != nil {
  128. return txErr
  129. }
  130. // setval is never rolled back by PostgreSQL, so sequences are resynced only
  131. // after the transaction has committed.
  132. if err := resetPostgresSequences(dst); err != nil {
  133. log.Printf("warning: failed to reset some postgres sequences: %v", err)
  134. }
  135. log.Printf("Migration complete: %d rows across %d tables.", totalRows, len(migrationModels()))
  136. log.Println("Set XUI_DB_TYPE=postgres and XUI_DB_DSN=... in /etc/default/x-ui, then restart x-ui.")
  137. return nil
  138. }
  139. // ExportPostgresToSQLite copies every row from the PostgreSQL database described
  140. // by srcDSN into a fresh SQLite file at dstPath. It is the reverse of
  141. // MigrateData and is used to hand a PostgreSQL-backed panel a portable .db file.
  142. // dstPath is created/overwritten; the PostgreSQL source is left untouched.
  143. func ExportPostgresToSQLite(srcDSN, dstPath string) error {
  144. if srcDSN == "" {
  145. return errors.New("source DSN is required")
  146. }
  147. if err := os.MkdirAll(path.Dir(dstPath), 0o755); err != nil {
  148. return err
  149. }
  150. // Start from an empty file so AutoMigrate creates the canonical schema.
  151. if err := os.Remove(dstPath); err != nil && !os.IsNotExist(err) {
  152. return err
  153. }
  154. src, err := gorm.Open(postgres.Open(srcDSN), &gorm.Config{Logger: logger.Discard})
  155. if err != nil {
  156. return fmt.Errorf("open postgres source: %w", err)
  157. }
  158. srcSQL, err := src.DB()
  159. if err != nil {
  160. return err
  161. }
  162. defer srcSQL.Close()
  163. // No WAL: keep all data in the main file so it is complete once closed.
  164. dst, err := gorm.Open(sqlite.Open(dstPath+"?_busy_timeout=10000"), &gorm.Config{Logger: logger.Discard})
  165. if err != nil {
  166. return fmt.Errorf("open sqlite destination: %w", err)
  167. }
  168. dstSQL, err := dst.DB()
  169. if err != nil {
  170. return err
  171. }
  172. defer dstSQL.Close()
  173. return copyAllModels(src, dst)
  174. }
  175. // copyAllModels (re)creates the schema on dst and copies every migrated table
  176. // from src to dst in FK-safe order. src/dst may be any gorm backend.
  177. func copyAllModels(src, dst *gorm.DB) error {
  178. for _, m := range migrationModels() {
  179. if err := dst.AutoMigrate(m); err != nil {
  180. return fmt.Errorf("AutoMigrate %T: %w", m, err)
  181. }
  182. }
  183. for _, m := range migrationModels() {
  184. if _, err := copyTable(src, dst, m); err != nil {
  185. return fmt.Errorf("copy %T: %w", m, err)
  186. }
  187. }
  188. return nil
  189. }
  190. func copyTable(src, dst *gorm.DB, mdl any) (int, error) {
  191. const batchSize = 500
  192. sliceType := reflect.SliceOf(reflect.PointerTo(reflect.TypeOf(mdl).Elem()))
  193. stmt := &gorm.Statement{DB: src}
  194. if err := stmt.Parse(mdl); err != nil {
  195. return 0, err
  196. }
  197. order := strings.Join(stmt.Schema.PrimaryFieldDBNames, ", ")
  198. table := stmt.Schema.Table
  199. columns := stmt.Schema.DBNames
  200. ctx := context.Background()
  201. total := 0
  202. for offset := 0; ; offset += batchSize {
  203. batchPtr := reflect.New(sliceType)
  204. q := src.Model(mdl).Limit(batchSize).Offset(offset)
  205. if order != "" {
  206. q = q.Order(order)
  207. }
  208. if err := q.Find(batchPtr.Interface()).Error; err != nil {
  209. return total, err
  210. }
  211. slice := batchPtr.Elem()
  212. n := slice.Len()
  213. if n == 0 {
  214. break
  215. }
  216. rows := make([]map[string]any, n)
  217. for i := range n {
  218. rv := reflect.Indirect(slice.Index(i))
  219. row := make(map[string]any, len(columns))
  220. for _, name := range columns {
  221. value, _ := stmt.Schema.FieldsByDBName[name].ValueOf(ctx, rv)
  222. row[name] = value
  223. }
  224. rows[i] = row
  225. }
  226. if err := dst.Table(table).CreateInBatches(rows, 200).Error; err != nil {
  227. return total, err
  228. }
  229. total += n
  230. if n < batchSize {
  231. break
  232. }
  233. }
  234. return total, nil
  235. }
  236. // truncatePostgresTables empties every migrated table on dst in a single
  237. // statement, resetting identity sequences. CASCADE covers the inbound/client
  238. // foreign keys regardless of insertion order. Only the panel's own tables are
  239. // touched, never the rest of the schema.
  240. func truncatePostgresTables(dst *gorm.DB, models []any) error {
  241. tables := make([]string, 0, len(models))
  242. for _, m := range models {
  243. stmt := &gorm.Statement{DB: dst}
  244. if err := stmt.Parse(m); err != nil {
  245. return err
  246. }
  247. tables = append(tables, `"`+stmt.Schema.Table+`"`)
  248. }
  249. if len(tables) == 0 {
  250. return nil
  251. }
  252. log.Println("Clearing destination tables...")
  253. return dst.Exec("TRUNCATE TABLE " + strings.Join(tables, ", ") + " RESTART IDENTITY CASCADE").Error
  254. }
  255. // resetPostgresSequences advances each migrated table's id sequence past MAX(id),
  256. // otherwise the next INSERT-without-id would clash with copied rows.
  257. func resetPostgresSequences(dst *gorm.DB) error {
  258. return resyncPostgresSequences(dst, migrationModels())
  259. }
  260. // resyncPostgresSequences sets each model's id sequence to MAX(id); idempotent. Id-less
  261. // composite-PK tables are skipped — Postgres rejects MAX(id) at parse time and logs it (#5665).
  262. func resyncPostgresSequences(db *gorm.DB, models []any) error {
  263. for _, m := range models {
  264. t, ok := tableWithIdColumn(db, m)
  265. if !ok {
  266. continue
  267. }
  268. // t comes from the trusted model set parsed by GORM, not user input, so
  269. // interpolating it as an identifier is safe. We ignore errors per-table.
  270. _ = db.Exec(
  271. `SELECT setval(pg_get_serial_sequence(?, 'id'), COALESCE((SELECT MAX(id) FROM "`+t+`"), 1), true)
  272. WHERE pg_get_serial_sequence(?, 'id') IS NOT NULL`,
  273. t, t,
  274. ).Error
  275. }
  276. return nil
  277. }
  278. // tableWithIdColumn resolves a model's table name and reports whether its GORM
  279. // schema maps an "id" database column.
  280. func tableWithIdColumn(db *gorm.DB, m any) (string, bool) {
  281. stmt := &gorm.Statement{DB: db}
  282. if err := stmt.Parse(m); err != nil {
  283. return "", false
  284. }
  285. if stmt.Schema == nil || stmt.Schema.LookUpField("id") == nil {
  286. return "", false
  287. }
  288. return stmt.Table, true
  289. }
  290. // PrepareSQLiteForMigration rejects SQLite files that are not a panel database
  291. // before the caller causes any downtime, then AutoMigrates the panel schema
  292. // onto the file so backups from older versions gain the newer tables and
  293. // columns the row copy reads. Data-level upgrades are not needed here: they
  294. // run dialect-agnostically on the destination via InitDB after the import.
  295. func PrepareSQLiteForMigration(dbPath string) error {
  296. gdb, err := gorm.Open(sqlite.Open(dbPath+"?_busy_timeout=10000"), &gorm.Config{Logger: logger.Discard})
  297. if err != nil {
  298. return err
  299. }
  300. sqlDB, err := gdb.DB()
  301. if err != nil {
  302. return err
  303. }
  304. defer sqlDB.Close()
  305. for _, table := range []string{"users", "settings", "inbounds"} {
  306. if !sqliteTableExists(sqlDB, table) {
  307. return fmt.Errorf("not a 3x-ui panel database: required table %q is missing", table)
  308. }
  309. }
  310. for _, m := range migrationModels() {
  311. if err := gdb.AutoMigrate(m); err != nil && !isIgnorableDuplicateColumnErr(gdb, err, m) {
  312. return fmt.Errorf("upgrade panel schema for %T: %w", m, err)
  313. }
  314. }
  315. return nil
  316. }