db.go 18 KB

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