db.go 18 KB

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