1
0

db.go 19 KB

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