db.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. // Package database provides database initialization, migration, and management utilities
  2. // for the 3x-ui panel using GORM with SQLite or PostgreSQL.
  3. package database
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "errors"
  8. "io"
  9. "log"
  10. "math"
  11. "os"
  12. "path"
  13. "slices"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/config"
  18. "github.com/mhsanaei/3x-ui/v3/database/model"
  19. "github.com/mhsanaei/3x-ui/v3/util/crypto"
  20. "github.com/mhsanaei/3x-ui/v3/util/random"
  21. "github.com/mhsanaei/3x-ui/v3/xray"
  22. "gorm.io/driver/postgres"
  23. "gorm.io/driver/sqlite"
  24. "gorm.io/gorm"
  25. "gorm.io/gorm/logger"
  26. )
  27. var db *gorm.DB
  28. const (
  29. DialectSQLite = "sqlite"
  30. DialectPostgres = "postgres"
  31. )
  32. // IsPostgres reports whether the active connection is a PostgreSQL backend.
  33. func IsPostgres() bool {
  34. if db == nil {
  35. return config.GetDBKind() == "postgres"
  36. }
  37. return db.Dialector.Name() == "postgres"
  38. }
  39. // Dialect returns the active GORM dialect name, or "" if the DB is not open.
  40. func Dialect() string {
  41. if db == nil {
  42. return ""
  43. }
  44. return db.Dialector.Name()
  45. }
  46. const (
  47. defaultUsername = "admin"
  48. defaultPassword = "admin"
  49. )
  50. func initModels() error {
  51. models := []any{
  52. &model.User{},
  53. &model.Inbound{},
  54. &model.OutboundTraffics{},
  55. &model.Setting{},
  56. &model.InboundClientIps{},
  57. &xray.ClientTraffic{},
  58. &model.HistoryOfSeeders{},
  59. &model.CustomGeoResource{},
  60. &model.Node{},
  61. &model.ApiToken{},
  62. &model.ClientRecord{},
  63. &model.ClientInbound{},
  64. &model.ClientGroup{},
  65. &model.InboundFallback{},
  66. &model.NodeClientTraffic{},
  67. }
  68. for _, mdl := range models {
  69. if err := db.AutoMigrate(mdl); err != nil {
  70. if isIgnorableDuplicateColumnErr(err, mdl) {
  71. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  72. continue
  73. }
  74. log.Printf("Error auto migrating model: %v", err)
  75. return err
  76. }
  77. }
  78. if err := dropLegacyForeignKeys(); err != nil {
  79. return err
  80. }
  81. if err := pruneOrphanedClientInbounds(); err != nil {
  82. return err
  83. }
  84. if IsPostgres() {
  85. if err := resyncPostgresSequences(db, models); err != nil {
  86. log.Printf("Error resyncing postgres sequences: %v", err)
  87. return err
  88. }
  89. }
  90. return nil
  91. }
  92. func dropLegacyForeignKeys() error {
  93. if !IsPostgres() {
  94. return nil
  95. }
  96. if err := db.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  97. log.Printf("Error dropping legacy foreign key fk_inbounds_client_stats: %v", err)
  98. return err
  99. }
  100. return nil
  101. }
  102. func pruneOrphanedClientInbounds() error {
  103. res := db.Exec("DELETE FROM client_inbounds WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  104. if res.Error != nil {
  105. log.Printf("Error pruning orphaned client_inbounds rows: %v", res.Error)
  106. return res.Error
  107. }
  108. if res.RowsAffected > 0 {
  109. log.Printf("Pruned %d orphaned client_inbounds row(s)", res.RowsAffected)
  110. }
  111. return nil
  112. }
  113. func isIgnorableDuplicateColumnErr(err error, mdl any) bool {
  114. if err == nil {
  115. return false
  116. }
  117. errMsg := strings.ToLower(err.Error())
  118. // SQLite: "duplicate column name: foo"
  119. // Postgres: `pq: column "foo" of relation "bar" already exists` / `sqlstate 42701`
  120. const sqlitePrefix = "duplicate column name:"
  121. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  122. col := strings.TrimSpace(after)
  123. col = strings.Trim(col, "`\"[]")
  124. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  125. }
  126. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  127. // Best effort: extract the column name between the first pair of double quotes.
  128. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  129. rest := after
  130. if e := strings.Index(rest, "\""); e > 0 {
  131. col := rest[:e]
  132. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  133. }
  134. }
  135. }
  136. return false
  137. }
  138. // initUser creates a default admin user if the users table is empty.
  139. func initUser() error {
  140. empty, err := isTableEmpty("users")
  141. if err != nil {
  142. log.Printf("Error checking if users table is empty: %v", err)
  143. return err
  144. }
  145. if empty {
  146. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  147. if err != nil {
  148. log.Printf("Error hashing default password: %v", err)
  149. return err
  150. }
  151. user := &model.User{
  152. Username: defaultUsername,
  153. Password: hashedPassword,
  154. }
  155. return db.Create(user).Error
  156. }
  157. return nil
  158. }
  159. // runSeeders migrates user passwords to bcrypt and records seeder execution to prevent re-running.
  160. func runSeeders(isUsersEmpty bool) error {
  161. empty, err := isTableEmpty("history_of_seeders")
  162. if err != nil {
  163. log.Printf("Error checking if users table is empty: %v", err)
  164. return err
  165. }
  166. if empty && isUsersEmpty {
  167. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix"}
  168. for _, name := range seeders {
  169. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  170. return err
  171. }
  172. }
  173. return seedApiTokens()
  174. }
  175. var seedersHistory []string
  176. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  177. log.Printf("Error fetching seeder history: %v", err)
  178. return err
  179. }
  180. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  181. var users []model.User
  182. if err := db.Find(&users).Error; err != nil {
  183. log.Printf("Error fetching users for password migration: %v", err)
  184. return err
  185. }
  186. for _, user := range users {
  187. if crypto.IsHashed(user.Password) {
  188. continue
  189. }
  190. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  191. if err != nil {
  192. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  193. return err
  194. }
  195. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  196. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  197. return err
  198. }
  199. }
  200. hashSeeder := &model.HistoryOfSeeders{
  201. SeederName: "UserPasswordHash",
  202. }
  203. if err := db.Create(hashSeeder).Error; err != nil {
  204. return err
  205. }
  206. }
  207. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  208. if err := seedApiTokens(); err != nil {
  209. return err
  210. }
  211. }
  212. if !slices.Contains(seedersHistory, "ClientsTable") {
  213. if err := seedClientsFromInboundJSON(); err != nil {
  214. return err
  215. }
  216. }
  217. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  218. if err := normalizeInboundClientsArray(); err != nil {
  219. return err
  220. }
  221. }
  222. if !slices.Contains(seedersHistory, "InboundClientTgIdFix") {
  223. if err := normalizeInboundClientTgId(); err != nil {
  224. return err
  225. }
  226. }
  227. if !slices.Contains(seedersHistory, "InboundClientSubIdFix") {
  228. if err := normalizeInboundClientSubId(); err != nil {
  229. return err
  230. }
  231. }
  232. if !slices.Contains(seedersHistory, "FreedomFinalRulesReverseFix") {
  233. if err := normalizeFreedomFinalRules(); err != nil {
  234. return err
  235. }
  236. }
  237. return nil
  238. }
  239. func normalizeInboundClientTgId() error {
  240. var inbounds []model.Inbound
  241. if err := db.Find(&inbounds).Error; err != nil {
  242. return err
  243. }
  244. return db.Transaction(func(tx *gorm.DB) error {
  245. for _, inbound := range inbounds {
  246. if strings.TrimSpace(inbound.Settings) == "" {
  247. continue
  248. }
  249. var settings map[string]any
  250. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  251. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  252. continue
  253. }
  254. clients, ok := settings["clients"].([]any)
  255. if !ok {
  256. continue
  257. }
  258. mutated := false
  259. for i, raw := range clients {
  260. obj, ok := raw.(map[string]any)
  261. if !ok {
  262. continue
  263. }
  264. tgRaw, present := obj["tgId"]
  265. if !present {
  266. continue
  267. }
  268. v, isFloat := tgRaw.(float64)
  269. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  270. continue
  271. }
  272. obj["tgId"] = int64(0)
  273. clients[i] = obj
  274. mutated = true
  275. }
  276. if !mutated {
  277. continue
  278. }
  279. settings["clients"] = clients
  280. newSettings, err := json.MarshalIndent(settings, "", " ")
  281. if err != nil {
  282. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  283. continue
  284. }
  285. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  286. Update("settings", string(newSettings)).Error; err != nil {
  287. return err
  288. }
  289. }
  290. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix"}).Error
  291. })
  292. }
  293. func normalizeInboundClientSubId() error {
  294. var inbounds []model.Inbound
  295. if err := db.Find(&inbounds).Error; err != nil {
  296. return err
  297. }
  298. return db.Transaction(func(tx *gorm.DB) error {
  299. for _, inbound := range inbounds {
  300. if strings.TrimSpace(inbound.Settings) == "" {
  301. continue
  302. }
  303. var settings map[string]any
  304. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  305. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  306. continue
  307. }
  308. clients, ok := settings["clients"].([]any)
  309. if !ok {
  310. continue
  311. }
  312. mutated := false
  313. for i, raw := range clients {
  314. obj, ok := raw.(map[string]any)
  315. if !ok {
  316. continue
  317. }
  318. existing, _ := obj["subId"].(string)
  319. if strings.TrimSpace(existing) != "" {
  320. continue
  321. }
  322. obj["subId"] = random.NumLower(16)
  323. clients[i] = obj
  324. mutated = true
  325. }
  326. if !mutated {
  327. continue
  328. }
  329. settings["clients"] = clients
  330. newSettings, err := json.MarshalIndent(settings, "", " ")
  331. if err != nil {
  332. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  333. continue
  334. }
  335. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  336. Update("settings", string(newSettings)).Error; err != nil {
  337. return err
  338. }
  339. }
  340. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  341. })
  342. }
  343. func normalizeInboundClientsArray() error {
  344. var inbounds []model.Inbound
  345. if err := db.Find(&inbounds).Error; err != nil {
  346. return err
  347. }
  348. return db.Transaction(func(tx *gorm.DB) error {
  349. for _, inbound := range inbounds {
  350. if strings.TrimSpace(inbound.Settings) == "" {
  351. continue
  352. }
  353. var settings map[string]any
  354. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  355. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  356. continue
  357. }
  358. raw, exists := settings["clients"]
  359. if !exists || raw != nil {
  360. continue
  361. }
  362. settings["clients"] = []any{}
  363. newSettings, err := json.MarshalIndent(settings, "", " ")
  364. if err != nil {
  365. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  366. continue
  367. }
  368. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  369. Update("settings", string(newSettings)).Error; err != nil {
  370. return err
  371. }
  372. }
  373. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  374. })
  375. }
  376. func normalizeFreedomFinalRules() error {
  377. var setting model.Setting
  378. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  379. if errors.Is(err, gorm.ErrRecordNotFound) {
  380. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  381. }
  382. if err != nil {
  383. return err
  384. }
  385. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  386. if rErr != nil {
  387. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  388. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  389. }
  390. return db.Transaction(func(tx *gorm.DB) error {
  391. if changed {
  392. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  393. Update("value", updated).Error; err != nil {
  394. return err
  395. }
  396. }
  397. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  398. })
  399. }
  400. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  401. if strings.TrimSpace(raw) == "" {
  402. return raw, false, nil
  403. }
  404. var cfg map[string]any
  405. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  406. return raw, false, err
  407. }
  408. outbounds, ok := cfg["outbounds"].([]any)
  409. if !ok {
  410. return raw, false, nil
  411. }
  412. changed := false
  413. for _, ob := range outbounds {
  414. obj, ok := ob.(map[string]any)
  415. if !ok {
  416. continue
  417. }
  418. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  419. continue
  420. }
  421. settings, ok := obj["settings"].(map[string]any)
  422. if !ok {
  423. continue
  424. }
  425. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  426. continue
  427. }
  428. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  429. changed = true
  430. }
  431. if !changed {
  432. return raw, false, nil
  433. }
  434. out, err := json.MarshalIndent(cfg, "", " ")
  435. if err != nil {
  436. return raw, false, err
  437. }
  438. return string(out), true, nil
  439. }
  440. func isLegacyPrivateOnlyFinalRules(v any) bool {
  441. rules, ok := v.([]any)
  442. if !ok || len(rules) != 1 {
  443. return false
  444. }
  445. rule, ok := rules[0].(map[string]any)
  446. if !ok {
  447. return false
  448. }
  449. if action, _ := rule["action"].(string); action != "allow" {
  450. return false
  451. }
  452. ips, ok := rule["ip"].([]any)
  453. if !ok || len(ips) != 1 {
  454. return false
  455. }
  456. if s, _ := ips[0].(string); s != "geoip:private" {
  457. return false
  458. }
  459. for k := range rule {
  460. if k != "action" && k != "ip" {
  461. return false
  462. }
  463. }
  464. return true
  465. }
  466. // normalizeClientJSONFields coerces loosely-typed numeric fields in a raw
  467. // settings.clients entry so json.Unmarshal into model.Client doesn't fail
  468. // when older rows wrote tgId/limitIp/totalGB/etc. as strings. Empty strings
  469. // drop the key so the field falls back to its zero value.
  470. func normalizeClientJSONFields(obj map[string]any) {
  471. normalizeInt := func(key string) {
  472. raw, exists := obj[key]
  473. if !exists {
  474. return
  475. }
  476. s, ok := raw.(string)
  477. if !ok {
  478. return
  479. }
  480. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  481. if trimmed == "" {
  482. delete(obj, key)
  483. return
  484. }
  485. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  486. obj[key] = n
  487. } else {
  488. delete(obj, key)
  489. }
  490. }
  491. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  492. normalizeInt(k)
  493. }
  494. }
  495. func seedClientsFromInboundJSON() error {
  496. var inbounds []model.Inbound
  497. if err := db.Find(&inbounds).Error; err != nil {
  498. return err
  499. }
  500. return db.Transaction(func(tx *gorm.DB) error {
  501. byEmail := map[string]*model.ClientRecord{}
  502. var existing []model.ClientRecord
  503. if err := tx.Find(&existing).Error; err != nil {
  504. return err
  505. }
  506. for i := range existing {
  507. byEmail[existing[i].Email] = &existing[i]
  508. }
  509. for _, inbound := range inbounds {
  510. if strings.TrimSpace(inbound.Settings) == "" {
  511. continue
  512. }
  513. var settings map[string]any
  514. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  515. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  516. continue
  517. }
  518. rawList, ok := settings["clients"].([]any)
  519. if !ok {
  520. continue
  521. }
  522. for _, raw := range rawList {
  523. obj, ok := raw.(map[string]any)
  524. if !ok {
  525. continue
  526. }
  527. normalizeClientJSONFields(obj)
  528. blob, err := json.Marshal(obj)
  529. if err != nil {
  530. continue
  531. }
  532. var c model.Client
  533. if err := json.Unmarshal(blob, &c); err != nil {
  534. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  535. inbound.Id, err, string(blob))
  536. continue
  537. }
  538. email := strings.TrimSpace(c.Email)
  539. if email == "" {
  540. continue
  541. }
  542. incoming := c.ToRecord()
  543. row, dup := byEmail[email]
  544. if !dup {
  545. if err := tx.Create(incoming).Error; err != nil {
  546. return err
  547. }
  548. byEmail[email] = incoming
  549. row = incoming
  550. } else {
  551. conflicts := model.MergeClientRecord(row, incoming)
  552. for _, x := range conflicts {
  553. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  554. email, x.Field, x.Old, x.New, x.Kept)
  555. }
  556. if err := tx.Save(row).Error; err != nil {
  557. return err
  558. }
  559. }
  560. link := model.ClientInbound{
  561. ClientId: row.Id,
  562. InboundId: inbound.Id,
  563. FlowOverride: c.Flow,
  564. }
  565. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  566. FirstOrCreate(&link).Error; err != nil {
  567. return err
  568. }
  569. }
  570. }
  571. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  572. })
  573. }
  574. // seedApiTokens copies the legacy `apiToken` setting into the new
  575. // api_tokens table as a row named "default" so existing central panels
  576. // keep working after the upgrade. Idempotent — records itself in
  577. // history_of_seeders and only runs when api_tokens is empty.
  578. func seedApiTokens() error {
  579. empty, err := isTableEmpty("api_tokens")
  580. if err != nil {
  581. return err
  582. }
  583. if empty {
  584. var legacy model.Setting
  585. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  586. if err == nil && legacy.Value != "" {
  587. row := &model.ApiToken{
  588. Name: "default",
  589. Token: legacy.Value,
  590. Enabled: true,
  591. }
  592. if err := db.Create(row).Error; err != nil {
  593. log.Printf("Error migrating legacy apiToken: %v", err)
  594. return err
  595. }
  596. }
  597. }
  598. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  599. }
  600. // isTableEmpty returns true if the named table contains zero rows.
  601. func isTableEmpty(tableName string) (bool, error) {
  602. var count int64
  603. err := db.Table(tableName).Count(&count).Error
  604. return count == 0, err
  605. }
  606. // InitDB sets up the database connection, migrates models, and runs seeders.
  607. // When XUI_DB_TYPE=postgres, dbPath is ignored and XUI_DB_DSN is used instead.
  608. func InitDB(dbPath string) error {
  609. var gormLogger logger.Interface
  610. if config.IsDebug() {
  611. gormLogger = logger.New(
  612. log.New(os.Stdout, "\r\n", log.LstdFlags),
  613. logger.Config{
  614. SlowThreshold: time.Second,
  615. LogLevel: logger.Info,
  616. IgnoreRecordNotFoundError: true,
  617. Colorful: true,
  618. },
  619. )
  620. } else {
  621. gormLogger = logger.Discard
  622. }
  623. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  624. var err error
  625. switch config.GetDBKind() {
  626. case "postgres":
  627. dsn := config.GetDBDSN()
  628. if dsn == "" {
  629. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  630. }
  631. db, err = gorm.Open(postgres.Open(dsn), c)
  632. if err != nil {
  633. return err
  634. }
  635. default:
  636. dir := path.Dir(dbPath)
  637. if err = os.MkdirAll(dir, 0755); err != nil {
  638. return err
  639. }
  640. dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=10000&_synchronous=NORMAL&_txlock=immediate"
  641. db, err = gorm.Open(sqlite.Open(dsn), c)
  642. if err != nil {
  643. return err
  644. }
  645. sqlDB, err := db.DB()
  646. if err != nil {
  647. return err
  648. }
  649. if _, err := sqlDB.Exec("PRAGMA journal_mode=WAL"); err != nil {
  650. return err
  651. }
  652. if _, err := sqlDB.Exec("PRAGMA busy_timeout=10000"); err != nil {
  653. return err
  654. }
  655. if _, err := sqlDB.Exec("PRAGMA synchronous=NORMAL"); err != nil {
  656. return err
  657. }
  658. }
  659. sqlDB, err := db.DB()
  660. if err != nil {
  661. return err
  662. }
  663. var maxOpen, maxIdle int
  664. switch config.GetDBKind() {
  665. case "postgres":
  666. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  667. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  668. default:
  669. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  670. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  671. }
  672. sqlDB.SetMaxOpenConns(maxOpen)
  673. sqlDB.SetMaxIdleConns(maxIdle)
  674. sqlDB.SetConnMaxLifetime(time.Hour)
  675. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  676. if err := initModels(); err != nil {
  677. return err
  678. }
  679. isUsersEmpty, err := isTableEmpty("users")
  680. if err != nil {
  681. return err
  682. }
  683. if err := initUser(); err != nil {
  684. return err
  685. }
  686. return runSeeders(isUsersEmpty)
  687. }
  688. func envInt(key string, def int) int {
  689. v := strings.TrimSpace(os.Getenv(key))
  690. if v == "" {
  691. return def
  692. }
  693. n, err := strconv.Atoi(v)
  694. if err != nil || n <= 0 {
  695. return def
  696. }
  697. return n
  698. }
  699. // CloseDB closes the database connection if it exists.
  700. func CloseDB() error {
  701. if db != nil {
  702. sqlDB, err := db.DB()
  703. if err != nil {
  704. return err
  705. }
  706. return sqlDB.Close()
  707. }
  708. return nil
  709. }
  710. // GetDB returns the global GORM database instance.
  711. func GetDB() *gorm.DB {
  712. return db
  713. }
  714. func IsNotFound(err error) bool {
  715. return errors.Is(err, gorm.ErrRecordNotFound)
  716. }
  717. // IsSQLiteDB checks if the given file is a valid SQLite database by reading its signature.
  718. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  719. signature := []byte("SQLite format 3\x00")
  720. buf := make([]byte, len(signature))
  721. _, err := file.ReadAt(buf, 0)
  722. if err != nil {
  723. return false, err
  724. }
  725. return bytes.Equal(buf, signature), nil
  726. }
  727. // Checkpoint performs a WAL checkpoint on the SQLite database to ensure data consistency.
  728. // No-op on PostgreSQL (WAL there is managed by the server).
  729. func Checkpoint() error {
  730. if IsPostgres() {
  731. return nil
  732. }
  733. return db.Exec("PRAGMA wal_checkpoint;").Error
  734. }
  735. // ValidateSQLiteDB opens the provided sqlite DB path with a throw-away connection
  736. // and runs a PRAGMA integrity_check to ensure the file is structurally sound.
  737. // It does not mutate global state or run migrations.
  738. func ValidateSQLiteDB(dbPath string) error {
  739. if _, err := os.Stat(dbPath); err != nil { // file must exist
  740. return err
  741. }
  742. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  743. if err != nil {
  744. return err
  745. }
  746. sqlDB, err := gdb.DB()
  747. if err != nil {
  748. return err
  749. }
  750. defer sqlDB.Close()
  751. var res string
  752. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  753. return err
  754. }
  755. if res != "ok" {
  756. return errors.New("sqlite integrity check failed: " + res)
  757. }
  758. return nil
  759. }