1
0

db.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. package database
  2. import (
  3. "bytes"
  4. "io"
  5. "io/fs"
  6. "os"
  7. "path"
  8. "x-ui/config"
  9. "x-ui/database/model"
  10. "x-ui/xray"
  11. "gorm.io/driver/sqlite"
  12. "gorm.io/gorm"
  13. "gorm.io/gorm/logger"
  14. )
  15. var db *gorm.DB
  16. var initializers = []func() error{
  17. initUser,
  18. initInbound,
  19. initOutbound,
  20. initSetting,
  21. initInboundClientIps,
  22. initClientTraffic,
  23. }
  24. func initUser() error {
  25. err := db.AutoMigrate(&model.User{})
  26. if err != nil {
  27. return err
  28. }
  29. var count int64
  30. err = db.Model(&model.User{}).Count(&count).Error
  31. if err != nil {
  32. return err
  33. }
  34. if count == 0 {
  35. user := &model.User{
  36. Username: "admin",
  37. Password: "admin",
  38. LoginSecret: "",
  39. }
  40. return db.Create(user).Error
  41. }
  42. return nil
  43. }
  44. func initInbound() error {
  45. return db.AutoMigrate(&model.Inbound{})
  46. }
  47. func initOutbound() error {
  48. return db.AutoMigrate(&model.OutboundTraffics{})
  49. }
  50. func initSetting() error {
  51. return db.AutoMigrate(&model.Setting{})
  52. }
  53. func initInboundClientIps() error {
  54. return db.AutoMigrate(&model.InboundClientIps{})
  55. }
  56. func initClientTraffic() error {
  57. return db.AutoMigrate(&xray.ClientTraffic{})
  58. }
  59. func InitDB(dbPath string) error {
  60. dir := path.Dir(dbPath)
  61. err := os.MkdirAll(dir, fs.ModePerm)
  62. if err != nil {
  63. return err
  64. }
  65. var gormLogger logger.Interface
  66. if config.IsDebug() {
  67. gormLogger = logger.Default
  68. } else {
  69. gormLogger = logger.Discard
  70. }
  71. c := &gorm.Config{
  72. Logger: gormLogger,
  73. }
  74. db, err = gorm.Open(sqlite.Open(dbPath), c)
  75. if err != nil {
  76. return err
  77. }
  78. for _, initialize := range initializers {
  79. if err := initialize(); err != nil {
  80. return err
  81. }
  82. }
  83. return nil
  84. }
  85. func GetDB() *gorm.DB {
  86. return db
  87. }
  88. func IsNotFound(err error) bool {
  89. return err == gorm.ErrRecordNotFound
  90. }
  91. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  92. signature := []byte("SQLite format 3\x00")
  93. buf := make([]byte, len(signature))
  94. _, err := file.ReadAt(buf, 0)
  95. if err != nil {
  96. return false, err
  97. }
  98. return bytes.Equal(buf, signature), nil
  99. }
  100. func Checkpoint() error {
  101. // Update WAL
  102. err := db.Exec("PRAGMA wal_checkpoint;").Error
  103. if err != nil {
  104. return err
  105. }
  106. return nil
  107. }