sqlite.go 900 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package db
  2. import (
  3. "os"
  4. "github.com/eryajf/chatgpt-dingtalk/pkg/logger"
  5. "github.com/glebarez/sqlite"
  6. "gorm.io/gorm"
  7. )
  8. // 全局数据库对象
  9. var DB *gorm.DB
  10. // 初始化数据库
  11. func InitDB() {
  12. DB = ConnSqlite()
  13. dbAutoMigrate()
  14. }
  15. // 自动迁移表结构
  16. func dbAutoMigrate() {
  17. _ = DB.AutoMigrate(
  18. Chat{},
  19. )
  20. }
  21. func ConnSqlite() *gorm.DB {
  22. err := os.MkdirAll("data", 0755)
  23. if err != nil {
  24. return nil
  25. }
  26. db, err := gorm.Open(sqlite.Open("data/dingtalkbot.sqlite"), &gorm.Config{
  27. // 禁用外键(指定外键时不会在mysql创建真实的外键约束)
  28. DisableForeignKeyConstraintWhenMigrating: true,
  29. })
  30. if err != nil {
  31. logger.Fatal("failed to connect sqlite3: %v", err)
  32. }
  33. dbObj, err := db.DB()
  34. if err != nil {
  35. logger.Fatal("failed to get sqlite3 obj: %v", err)
  36. }
  37. // 参见: https://github.com/glebarez/sqlite/issues/52
  38. dbObj.SetMaxOpenConns(1)
  39. return db
  40. }