models.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. _ "github.com/go-sql-driver/mysql"
  9. _ "github.com/lib/pq"
  10. "github.com/lunny/xorm"
  11. "github.com/gogits/gogs/modules/base"
  12. )
  13. var orm *xorm.Engine
  14. func setEngine() {
  15. dbType := base.Cfg.MustValue("database", "DB_TYPE")
  16. dbHost := base.Cfg.MustValue("database", "HOST")
  17. dbName := base.Cfg.MustValue("database", "NAME")
  18. dbUser := base.Cfg.MustValue("database", "USER")
  19. dbPwd := base.Cfg.MustValue("database", "PASSWD")
  20. sslMode := base.Cfg.MustValue("database", "SSL_MODE")
  21. var err error
  22. switch dbType {
  23. case "mysql":
  24. orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@%s/%s?charset=utf8",
  25. dbUser, dbPwd, dbHost, dbName))
  26. case "postgres":
  27. orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
  28. dbUser, dbPwd, dbName, sslMode))
  29. default:
  30. fmt.Printf("Unknown database type: %s\n", dbType)
  31. os.Exit(2)
  32. }
  33. if err != nil {
  34. fmt.Printf("models.init(fail to conntect database): %v\n", err)
  35. os.Exit(2)
  36. }
  37. // WARNNING: for serv command, MUST remove the output to os.stdout,
  38. // so use log file to instead print to stdout.
  39. //x.ShowDebug = true
  40. //orm.ShowErr = true
  41. f, err := os.Create("xorm.log")
  42. if err != nil {
  43. fmt.Printf("models.init(fail to create xorm.log): %v\n", err)
  44. os.Exit(2)
  45. }
  46. orm.Logger = f
  47. orm.ShowSQL = true
  48. }
  49. func init() {
  50. setEngine()
  51. if err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch),
  52. new(Action), new(Access)); err != nil {
  53. fmt.Printf("sync database struct error: %v\n", err)
  54. os.Exit(2)
  55. }
  56. }
  57. type Statistic struct {
  58. Counter struct {
  59. User, PublicKey, Repo, Watch, Action, Access int64
  60. }
  61. }
  62. func GetStatistic() (stats Statistic) {
  63. stats.Counter.User, _ = orm.Count(new(User))
  64. stats.Counter.PublicKey, _ = orm.Count(new(PublicKey))
  65. stats.Counter.Repo, _ = orm.Count(new(Repository))
  66. stats.Counter.Watch, _ = orm.Count(new(Watch))
  67. stats.Counter.Action, _ = orm.Count(new(Action))
  68. stats.Counter.Access, _ = orm.Count(new(Access))
  69. return stats
  70. }