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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. new(DeletedBranch),
  105. )
  106. gonicNames := []string{"SSL", "UID"}
  107. for _, name := range gonicNames {
  108. core.LintGonicMapper[name] = true
  109. }
  110. }
  111. // LoadConfigs loads the database settings
  112. func LoadConfigs() {
  113. sec := setting.Cfg.Section("database")
  114. DbCfg.Type = sec.Key("DB_TYPE").String()
  115. switch DbCfg.Type {
  116. case "sqlite3":
  117. setting.UseSQLite3 = true
  118. case "mysql":
  119. setting.UseMySQL = true
  120. case "postgres":
  121. setting.UsePostgreSQL = true
  122. case "tidb":
  123. setting.UseTiDB = true
  124. case "mssql":
  125. setting.UseMSSQL = true
  126. }
  127. DbCfg.Host = sec.Key("HOST").String()
  128. DbCfg.Name = sec.Key("NAME").String()
  129. DbCfg.User = sec.Key("USER").String()
  130. if len(DbCfg.Passwd) == 0 {
  131. DbCfg.Passwd = sec.Key("PASSWD").String()
  132. }
  133. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  134. DbCfg.Path = sec.Key("PATH").MustString("data/gitea.db")
  135. DbCfg.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  136. sec = setting.Cfg.Section("indexer")
  137. setting.Indexer.IssuePath = sec.Key("ISSUE_INDEXER_PATH").MustString("indexers/issues.bleve")
  138. setting.Indexer.UpdateQueueLength = sec.Key("UPDATE_BUFFER_LEN").MustInt(20)
  139. }
  140. // parsePostgreSQLHostPort parses given input in various forms defined in
  141. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  142. // and returns proper host and port number.
  143. func parsePostgreSQLHostPort(info string) (string, string) {
  144. host, port := "127.0.0.1", "5432"
  145. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  146. idx := strings.LastIndex(info, ":")
  147. host = info[:idx]
  148. port = info[idx+1:]
  149. } else if len(info) > 0 {
  150. host = info
  151. }
  152. return host, port
  153. }
  154. func parseMSSQLHostPort(info string) (string, string) {
  155. host, port := "127.0.0.1", "1433"
  156. if strings.Contains(info, ":") {
  157. host = strings.Split(info, ":")[0]
  158. port = strings.Split(info, ":")[1]
  159. } else if strings.Contains(info, ",") {
  160. host = strings.Split(info, ",")[0]
  161. port = strings.TrimSpace(strings.Split(info, ",")[1])
  162. } else if len(info) > 0 {
  163. host = info
  164. }
  165. return host, port
  166. }
  167. func getEngine() (*xorm.Engine, error) {
  168. connStr := ""
  169. var Param = "?"
  170. if strings.Contains(DbCfg.Name, Param) {
  171. Param = "&"
  172. }
  173. switch DbCfg.Type {
  174. case "mysql":
  175. if DbCfg.Host[0] == '/' { // looks like a unix socket
  176. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  177. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  178. } else {
  179. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  180. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  181. }
  182. case "postgres":
  183. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  184. if host[0] == '/' { // looks like a unix socket
  185. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  186. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  187. } else {
  188. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  189. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  190. }
  191. case "mssql":
  192. host, port := parseMSSQLHostPort(DbCfg.Host)
  193. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  194. case "sqlite3":
  195. if !EnableSQLite3 {
  196. return nil, errors.New("this binary version does not build support for SQLite3")
  197. }
  198. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  199. return nil, fmt.Errorf("Failed to create directories: %v", err)
  200. }
  201. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", DbCfg.Path, DbCfg.Timeout)
  202. case "tidb":
  203. if !EnableTiDB {
  204. return nil, errors.New("this binary version does not build support for TiDB")
  205. }
  206. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  207. return nil, fmt.Errorf("Failed to create directories: %v", err)
  208. }
  209. connStr = "goleveldb://" + DbCfg.Path
  210. default:
  211. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  212. }
  213. return xorm.NewEngine(DbCfg.Type, connStr)
  214. }
  215. // NewTestEngine sets a new test xorm.Engine
  216. func NewTestEngine(x *xorm.Engine) (err error) {
  217. x, err = getEngine()
  218. if err != nil {
  219. return fmt.Errorf("Connect to database: %v", err)
  220. }
  221. x.SetMapper(core.GonicMapper{})
  222. x.SetLogger(log.XORMLogger)
  223. x.ShowSQL(!setting.ProdMode)
  224. return x.StoreEngine("InnoDB").Sync2(tables...)
  225. }
  226. // SetEngine sets the xorm.Engine
  227. func SetEngine() (err error) {
  228. x, err = getEngine()
  229. if err != nil {
  230. return fmt.Errorf("Failed to connect to database: %v", err)
  231. }
  232. x.SetMapper(core.GonicMapper{})
  233. // WARNING: for serv command, MUST remove the output to os.stdout,
  234. // so use log file to instead print to stdout.
  235. x.SetLogger(log.XORMLogger)
  236. x.ShowSQL(true)
  237. return nil
  238. }
  239. // NewEngine initializes a new xorm.Engine
  240. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  241. if err = SetEngine(); err != nil {
  242. return err
  243. }
  244. if err = x.Ping(); err != nil {
  245. return err
  246. }
  247. if err = migrateFunc(x); err != nil {
  248. return fmt.Errorf("migrate: %v", err)
  249. }
  250. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  251. return fmt.Errorf("sync database struct error: %v", err)
  252. }
  253. return nil
  254. }
  255. // Statistic contains the database statistics
  256. type Statistic struct {
  257. Counter struct {
  258. User, Org, PublicKey,
  259. Repo, Watch, Star, Action, Access,
  260. Issue, Comment, Oauth, Follow,
  261. Mirror, Release, LoginSource, Webhook,
  262. Milestone, Label, HookTask,
  263. Team, UpdateTask, Attachment int64
  264. }
  265. }
  266. // GetStatistic returns the database statistics
  267. func GetStatistic() (stats Statistic) {
  268. stats.Counter.User = CountUsers()
  269. stats.Counter.Org = CountOrganizations()
  270. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  271. stats.Counter.Repo = CountRepositories(true)
  272. stats.Counter.Watch, _ = x.Count(new(Watch))
  273. stats.Counter.Star, _ = x.Count(new(Star))
  274. stats.Counter.Action, _ = x.Count(new(Action))
  275. stats.Counter.Access, _ = x.Count(new(Access))
  276. stats.Counter.Issue, _ = x.Count(new(Issue))
  277. stats.Counter.Comment, _ = x.Count(new(Comment))
  278. stats.Counter.Oauth = 0
  279. stats.Counter.Follow, _ = x.Count(new(Follow))
  280. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  281. stats.Counter.Release, _ = x.Count(new(Release))
  282. stats.Counter.LoginSource = CountLoginSources()
  283. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  284. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  285. stats.Counter.Label, _ = x.Count(new(Label))
  286. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  287. stats.Counter.Team, _ = x.Count(new(Team))
  288. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  289. return
  290. }
  291. // Ping tests if database is alive
  292. func Ping() error {
  293. return x.Ping()
  294. }
  295. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  296. func DumpDatabase(filePath string, dbType string) error {
  297. var tbs []*core.Table
  298. for _, t := range tables {
  299. tbs = append(tbs, x.TableInfo(t).Table)
  300. }
  301. if len(dbType) > 0 {
  302. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  303. }
  304. return x.DumpTablesToFile(tbs, filePath)
  305. }