db.go 18 KB

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