sqlite.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package db
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/jinzhu/gorm"
  6. _ "github.com/jinzhu/gorm/dialects/sqlite"
  7. "github.com/penggy/EasyGoLib/utils"
  8. )
  9. type Model struct {
  10. ID string `structs:"id" gorm:"primary_key" form:"id" json:"id"`
  11. CreatedAt utils.DateTime `structs:"-" json:"createdAt" gorm:"type:datetime"`
  12. UpdatedAt utils.DateTime `structs:"-" json:"updatedAt" gorm:"type:datetime"`
  13. // DeletedAt *time.Time `sql:"index" structs:"-"`
  14. }
  15. var SQLite *gorm.DB
  16. func Init() (err error) {
  17. gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTablename string) string {
  18. return "t_" + defaultTablename
  19. }
  20. dbFile := utils.DBFile()
  21. log.Println("db file -->", utils.DBFile())
  22. SQLite, err = gorm.Open("sqlite3", fmt.Sprintf("%s?loc=Asia/Shanghai", dbFile))
  23. if err != nil {
  24. return
  25. }
  26. // Sqlite cannot handle concurrent writes, so we limit sqlite to one connection.
  27. // see https://github.com/mattn/go-sqlite3/issues/274
  28. SQLite.DB().SetMaxOpenConns(1)
  29. SQLite.SetLogger(DefaultGormLogger)
  30. SQLite.LogMode(false)
  31. return
  32. }
  33. func Close() {
  34. if SQLite != nil {
  35. SQLite.Close()
  36. SQLite = nil
  37. }
  38. }