models.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "os"
  8. "path"
  9. _ "github.com/go-sql-driver/mysql"
  10. _ "github.com/lib/pq"
  11. "github.com/lunny/xorm"
  12. "github.com/gogits/gogs/modules/base"
  13. )
  14. var orm *xorm.Engine
  15. func setEngine() {
  16. dbType := base.Cfg.MustValue("database", "DB_TYPE")
  17. dbHost := base.Cfg.MustValue("database", "HOST")
  18. dbName := base.Cfg.MustValue("database", "NAME")
  19. dbUser := base.Cfg.MustValue("database", "USER")
  20. dbPwd := base.Cfg.MustValue("database", "PASSWD")
  21. dbPath := base.Cfg.MustValue("database", "PATH", "data/gogs.db")
  22. sslMode := base.Cfg.MustValue("database", "SSL_MODE")
  23. var err error
  24. switch dbType {
  25. case "mysql":
  26. orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@%s/%s?charset=utf8",
  27. dbUser, dbPwd, dbHost, dbName))
  28. case "postgres":
  29. orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
  30. dbUser, dbPwd, dbName, sslMode))
  31. case "sqlite3":
  32. os.MkdirAll(path.Dir(dbPath), os.ModePerm)
  33. orm, err = xorm.NewEngine("sqlite3", dbPath)
  34. default:
  35. fmt.Printf("Unknown database type: %s\n", dbType)
  36. os.Exit(2)
  37. }
  38. if err != nil {
  39. fmt.Printf("models.init(fail to conntect database): %v\n", err)
  40. os.Exit(2)
  41. }
  42. // WARNNING: for serv command, MUST remove the output to os.stdout,
  43. // so use log file to instead print to stdout.
  44. //x.ShowDebug = true
  45. //orm.ShowErr = true
  46. f, err := os.Create("xorm.log")
  47. if err != nil {
  48. fmt.Printf("models.init(fail to create xorm.log): %v\n", err)
  49. os.Exit(2)
  50. }
  51. orm.Logger = f
  52. orm.ShowSQL = true
  53. }
  54. func init() {
  55. setEngine()
  56. if err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch),
  57. new(Action), new(Access)); err != nil {
  58. fmt.Printf("sync database struct error: %v\n", err)
  59. os.Exit(2)
  60. }
  61. }
  62. type Statistic struct {
  63. Counter struct {
  64. User, PublicKey, Repo, Watch, Action, Access int64
  65. }
  66. }
  67. func GetStatistic() (stats Statistic) {
  68. stats.Counter.User, _ = orm.Count(new(User))
  69. stats.Counter.PublicKey, _ = orm.Count(new(PublicKey))
  70. stats.Counter.Repo, _ = orm.Count(new(Repository))
  71. stats.Counter.Watch, _ = orm.Count(new(Watch))
  72. stats.Counter.Action, _ = orm.Count(new(Action))
  73. stats.Counter.Access, _ = orm.Count(new(Access))
  74. return stats
  75. }