You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.go 9.6 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
9 years ago
10 years ago
10 years ago
11 years ago
11 years ago
8 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. "database/sql"
  7. "errors"
  8. "fmt"
  9. "net/url"
  10. "os"
  11. "path"
  12. "strings"
  13. // Needed for the MySQL driver
  14. _ "github.com/go-sql-driver/mysql"
  15. "github.com/go-xorm/core"
  16. "github.com/go-xorm/xorm"
  17. // Needed for the Postgresql driver
  18. _ "github.com/lib/pq"
  19. // Needed for the MSSSQL driver
  20. _ "github.com/denisenkom/go-mssqldb"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/setting"
  23. )
  24. // Engine represents a xorm engine or session.
  25. type Engine interface {
  26. Table(tableNameOrBean interface{}) *xorm.Session
  27. Count(...interface{}) (int64, error)
  28. Decr(column string, arg ...interface{}) *xorm.Session
  29. Delete(interface{}) (int64, error)
  30. Exec(string, ...interface{}) (sql.Result, error)
  31. Find(interface{}, ...interface{}) error
  32. Get(interface{}) (bool, error)
  33. Id(interface{}) *xorm.Session
  34. In(string, ...interface{}) *xorm.Session
  35. Incr(column string, arg ...interface{}) *xorm.Session
  36. Insert(...interface{}) (int64, error)
  37. InsertOne(interface{}) (int64, error)
  38. Iterate(interface{}, xorm.IterFunc) error
  39. Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session
  40. SQL(interface{}, ...interface{}) *xorm.Session
  41. Where(interface{}, ...interface{}) *xorm.Session
  42. }
  43. var (
  44. x *xorm.Engine
  45. tables []interface{}
  46. // HasEngine specifies if we have a xorm.Engine
  47. HasEngine bool
  48. // DbCfg holds the database settings
  49. DbCfg struct {
  50. Type, Host, Name, User, Passwd, Path, SSLMode string
  51. Timeout int
  52. }
  53. // EnableSQLite3 use SQLite3
  54. EnableSQLite3 bool
  55. // EnableTiDB enable TiDB
  56. EnableTiDB bool
  57. )
  58. func init() {
  59. tables = append(tables,
  60. new(User),
  61. new(PublicKey),
  62. new(AccessToken),
  63. new(Repository),
  64. new(DeployKey),
  65. new(Collaboration),
  66. new(Access),
  67. new(Upload),
  68. new(Watch),
  69. new(Star),
  70. new(Follow),
  71. new(Action),
  72. new(Issue),
  73. new(PullRequest),
  74. new(Comment),
  75. new(Attachment),
  76. new(Label),
  77. new(IssueLabel),
  78. new(Milestone),
  79. new(Mirror),
  80. new(Release),
  81. new(LoginSource),
  82. new(Webhook),
  83. new(HookTask),
  84. new(Team),
  85. new(OrgUser),
  86. new(TeamUser),
  87. new(TeamRepo),
  88. new(Notice),
  89. new(EmailAddress),
  90. new(Notification),
  91. new(IssueUser),
  92. new(LFSMetaObject),
  93. new(TwoFactor),
  94. new(GPGKey),
  95. new(RepoUnit),
  96. new(RepoRedirect),
  97. new(ExternalLoginUser),
  98. new(ProtectedBranch),
  99. new(UserOpenID),
  100. new(IssueWatch),
  101. new(CommitStatus),
  102. new(Stopwatch),
  103. new(TrackedTime),
  104. )
  105. gonicNames := []string{"SSL", "UID"}
  106. for _, name := range gonicNames {
  107. core.LintGonicMapper[name] = true
  108. }
  109. }
  110. // LoadConfigs loads the database settings
  111. func LoadConfigs() {
  112. sec := setting.Cfg.Section("database")
  113. DbCfg.Type = sec.Key("DB_TYPE").String()
  114. switch DbCfg.Type {
  115. case "sqlite3":
  116. setting.UseSQLite3 = true
  117. case "mysql":
  118. setting.UseMySQL = true
  119. case "postgres":
  120. setting.UsePostgreSQL = true
  121. case "tidb":
  122. setting.UseTiDB = true
  123. case "mssql":
  124. setting.UseMSSQL = true
  125. }
  126. DbCfg.Host = sec.Key("HOST").String()
  127. DbCfg.Name = sec.Key("NAME").String()
  128. DbCfg.User = sec.Key("USER").String()
  129. if len(DbCfg.Passwd) == 0 {
  130. DbCfg.Passwd = sec.Key("PASSWD").String()
  131. }
  132. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  133. DbCfg.Path = sec.Key("PATH").MustString("data/gitea.db")
  134. DbCfg.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  135. sec = setting.Cfg.Section("indexer")
  136. setting.Indexer.IssuePath = sec.Key("ISSUE_INDEXER_PATH").MustString("indexers/issues.bleve")
  137. setting.Indexer.UpdateQueueLength = sec.Key("UPDATE_BUFFER_LEN").MustInt(20)
  138. }
  139. // parsePostgreSQLHostPort parses given input in various forms defined in
  140. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  141. // and returns proper host and port number.
  142. func parsePostgreSQLHostPort(info string) (string, string) {
  143. host, port := "127.0.0.1", "5432"
  144. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  145. idx := strings.LastIndex(info, ":")
  146. host = info[:idx]
  147. port = info[idx+1:]
  148. } else if len(info) > 0 {
  149. host = info
  150. }
  151. return host, port
  152. }
  153. func parseMSSQLHostPort(info string) (string, string) {
  154. host, port := "127.0.0.1", "1433"
  155. if strings.Contains(info, ":") {
  156. host = strings.Split(info, ":")[0]
  157. port = strings.Split(info, ":")[1]
  158. } else if strings.Contains(info, ",") {
  159. host = strings.Split(info, ",")[0]
  160. port = strings.TrimSpace(strings.Split(info, ",")[1])
  161. } else if len(info) > 0 {
  162. host = info
  163. }
  164. return host, port
  165. }
  166. func getEngine() (*xorm.Engine, error) {
  167. connStr := ""
  168. var Param = "?"
  169. if strings.Contains(DbCfg.Name, Param) {
  170. Param = "&"
  171. }
  172. switch DbCfg.Type {
  173. case "mysql":
  174. if DbCfg.Host[0] == '/' { // looks like a unix socket
  175. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  176. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  177. } else {
  178. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  179. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  180. }
  181. case "postgres":
  182. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  183. if host[0] == '/' { // looks like a unix socket
  184. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  185. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  186. } else {
  187. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  188. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  189. }
  190. case "mssql":
  191. host, port := parseMSSQLHostPort(DbCfg.Host)
  192. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  193. case "sqlite3":
  194. if !EnableSQLite3 {
  195. return nil, errors.New("this binary version does not build support for SQLite3")
  196. }
  197. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  198. return nil, fmt.Errorf("Failed to create directories: %v", err)
  199. }
  200. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", DbCfg.Path, DbCfg.Timeout)
  201. case "tidb":
  202. if !EnableTiDB {
  203. return nil, errors.New("this binary version does not build support for TiDB")
  204. }
  205. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  206. return nil, fmt.Errorf("Failed to create directories: %v", err)
  207. }
  208. connStr = "goleveldb://" + DbCfg.Path
  209. default:
  210. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  211. }
  212. return xorm.NewEngine(DbCfg.Type, connStr)
  213. }
  214. // NewTestEngine sets a new test xorm.Engine
  215. func NewTestEngine(x *xorm.Engine) (err error) {
  216. x, err = getEngine()
  217. if err != nil {
  218. return fmt.Errorf("Connect to database: %v", err)
  219. }
  220. x.SetMapper(core.GonicMapper{})
  221. x.SetLogger(log.XORMLogger)
  222. x.ShowSQL(!setting.ProdMode)
  223. return x.StoreEngine("InnoDB").Sync2(tables...)
  224. }
  225. // SetEngine sets the xorm.Engine
  226. func SetEngine() (err error) {
  227. x, err = getEngine()
  228. if err != nil {
  229. return fmt.Errorf("Failed to connect to database: %v", err)
  230. }
  231. x.SetMapper(core.GonicMapper{})
  232. // WARNING: for serv command, MUST remove the output to os.stdout,
  233. // so use log file to instead print to stdout.
  234. x.SetLogger(log.XORMLogger)
  235. x.ShowSQL(true)
  236. return nil
  237. }
  238. // NewEngine initializes a new xorm.Engine
  239. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  240. if err = SetEngine(); err != nil {
  241. return err
  242. }
  243. if err = x.Ping(); err != nil {
  244. return err
  245. }
  246. if err = migrateFunc(x); err != nil {
  247. return fmt.Errorf("migrate: %v", err)
  248. }
  249. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  250. return fmt.Errorf("sync database struct error: %v", err)
  251. }
  252. return nil
  253. }
  254. // Statistic contains the database statistics
  255. type Statistic struct {
  256. Counter struct {
  257. User, Org, PublicKey,
  258. Repo, Watch, Star, Action, Access,
  259. Issue, Comment, Oauth, Follow,
  260. Mirror, Release, LoginSource, Webhook,
  261. Milestone, Label, HookTask,
  262. Team, UpdateTask, Attachment int64
  263. }
  264. }
  265. // GetStatistic returns the database statistics
  266. func GetStatistic() (stats Statistic) {
  267. stats.Counter.User = CountUsers()
  268. stats.Counter.Org = CountOrganizations()
  269. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  270. stats.Counter.Repo = CountRepositories(true)
  271. stats.Counter.Watch, _ = x.Count(new(Watch))
  272. stats.Counter.Star, _ = x.Count(new(Star))
  273. stats.Counter.Action, _ = x.Count(new(Action))
  274. stats.Counter.Access, _ = x.Count(new(Access))
  275. stats.Counter.Issue, _ = x.Count(new(Issue))
  276. stats.Counter.Comment, _ = x.Count(new(Comment))
  277. stats.Counter.Oauth = 0
  278. stats.Counter.Follow, _ = x.Count(new(Follow))
  279. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  280. stats.Counter.Release, _ = x.Count(new(Release))
  281. stats.Counter.LoginSource = CountLoginSources()
  282. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  283. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  284. stats.Counter.Label, _ = x.Count(new(Label))
  285. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  286. stats.Counter.Team, _ = x.Count(new(Team))
  287. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  288. return
  289. }
  290. // Ping tests if database is alive
  291. func Ping() error {
  292. return x.Ping()
  293. }
  294. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  295. func DumpDatabase(filePath string, dbType string) error {
  296. var tbs []*core.Table
  297. for _, t := range tables {
  298. tbs = append(tbs, x.TableInfo(t).Table)
  299. }
  300. if len(dbType) > 0 {
  301. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  302. }
  303. return x.DumpTablesToFile(tbs, filePath)
  304. }