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.

models.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "database/sql"
  8. "errors"
  9. "fmt"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/setting"
  17. // Needed for the MySQL driver
  18. _ "github.com/go-sql-driver/mysql"
  19. "github.com/go-xorm/core"
  20. "github.com/go-xorm/xorm"
  21. // Needed for the Postgresql driver
  22. _ "github.com/lib/pq"
  23. // Needed for the MSSSQL driver
  24. _ "github.com/denisenkom/go-mssqldb"
  25. )
  26. // Engine represents a xorm engine or session.
  27. type Engine interface {
  28. Table(tableNameOrBean interface{}) *xorm.Session
  29. Count(...interface{}) (int64, error)
  30. Decr(column string, arg ...interface{}) *xorm.Session
  31. Delete(interface{}) (int64, error)
  32. Exec(...interface{}) (sql.Result, error)
  33. Find(interface{}, ...interface{}) error
  34. Get(interface{}) (bool, error)
  35. ID(interface{}) *xorm.Session
  36. In(string, ...interface{}) *xorm.Session
  37. Incr(column string, arg ...interface{}) *xorm.Session
  38. Insert(...interface{}) (int64, error)
  39. InsertOne(interface{}) (int64, error)
  40. Iterate(interface{}, xorm.IterFunc) error
  41. Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session
  42. SQL(interface{}, ...interface{}) *xorm.Session
  43. Where(interface{}, ...interface{}) *xorm.Session
  44. }
  45. var (
  46. x *xorm.Engine
  47. supportedDatabases = []string{"mysql", "postgres", "mssql"}
  48. tables []interface{}
  49. // HasEngine specifies if we have a xorm.Engine
  50. HasEngine bool
  51. // DbCfg holds the database settings
  52. DbCfg struct {
  53. Type, Host, Name, User, Passwd, Path, SSLMode, Charset string
  54. Timeout int
  55. }
  56. // EnableSQLite3 use SQLite3
  57. EnableSQLite3 bool
  58. // EnableTiDB enable TiDB
  59. EnableTiDB bool
  60. )
  61. func init() {
  62. tables = append(tables,
  63. new(User),
  64. new(PublicKey),
  65. new(AccessToken),
  66. new(Repository),
  67. new(DeployKey),
  68. new(Collaboration),
  69. new(Access),
  70. new(Upload),
  71. new(Watch),
  72. new(Star),
  73. new(Follow),
  74. new(Action),
  75. new(Issue),
  76. new(PullRequest),
  77. new(Comment),
  78. new(Attachment),
  79. new(Label),
  80. new(IssueLabel),
  81. new(Milestone),
  82. new(Mirror),
  83. new(Release),
  84. new(LoginSource),
  85. new(Webhook),
  86. new(HookTask),
  87. new(Team),
  88. new(OrgUser),
  89. new(TeamUser),
  90. new(TeamRepo),
  91. new(Notice),
  92. new(EmailAddress),
  93. new(Notification),
  94. new(IssueUser),
  95. new(LFSMetaObject),
  96. new(TwoFactor),
  97. new(GPGKey),
  98. new(GPGKeyImport),
  99. new(RepoUnit),
  100. new(RepoRedirect),
  101. new(ExternalLoginUser),
  102. new(ProtectedBranch),
  103. new(UserOpenID),
  104. new(IssueWatch),
  105. new(CommitStatus),
  106. new(Stopwatch),
  107. new(TrackedTime),
  108. new(DeletedBranch),
  109. new(RepoIndexerStatus),
  110. new(IssueDependency),
  111. new(LFSLock),
  112. new(Reaction),
  113. new(IssueAssignees),
  114. new(U2FRegistration),
  115. new(TeamUnit),
  116. new(Review),
  117. new(OAuth2Application),
  118. new(OAuth2AuthorizationCode),
  119. new(OAuth2Grant),
  120. )
  121. gonicNames := []string{"SSL", "UID"}
  122. for _, name := range gonicNames {
  123. core.LintGonicMapper[name] = true
  124. }
  125. }
  126. // LoadConfigs loads the database settings
  127. func LoadConfigs() {
  128. sec := setting.Cfg.Section("database")
  129. DbCfg.Type = sec.Key("DB_TYPE").String()
  130. switch DbCfg.Type {
  131. case "sqlite3":
  132. setting.UseSQLite3 = true
  133. case "mysql":
  134. setting.UseMySQL = true
  135. case "postgres":
  136. setting.UsePostgreSQL = true
  137. case "tidb":
  138. setting.UseTiDB = true
  139. case "mssql":
  140. setting.UseMSSQL = true
  141. }
  142. DbCfg.Host = sec.Key("HOST").String()
  143. DbCfg.Name = sec.Key("NAME").String()
  144. DbCfg.User = sec.Key("USER").String()
  145. if len(DbCfg.Passwd) == 0 {
  146. DbCfg.Passwd = sec.Key("PASSWD").String()
  147. }
  148. DbCfg.SSLMode = sec.Key("SSL_MODE").MustString("disable")
  149. DbCfg.Charset = sec.Key("CHARSET").In("utf8", []string{"utf8", "utf8mb4"})
  150. DbCfg.Path = sec.Key("PATH").MustString(filepath.Join(setting.AppDataPath, "gitea.db"))
  151. DbCfg.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  152. }
  153. // parsePostgreSQLHostPort parses given input in various forms defined in
  154. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  155. // and returns proper host and port number.
  156. func parsePostgreSQLHostPort(info string) (string, string) {
  157. host, port := "127.0.0.1", "5432"
  158. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  159. idx := strings.LastIndex(info, ":")
  160. host = info[:idx]
  161. port = info[idx+1:]
  162. } else if len(info) > 0 {
  163. host = info
  164. }
  165. return host, port
  166. }
  167. func getPostgreSQLConnectionString(DBHost, DBUser, DBPasswd, DBName, DBParam, DBSSLMode string) (connStr string) {
  168. host, port := parsePostgreSQLHostPort(DBHost)
  169. if host[0] == '/' { // looks like a unix socket
  170. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  171. url.PathEscape(DBUser), url.PathEscape(DBPasswd), port, DBName, DBParam, DBSSLMode, host)
  172. } else {
  173. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  174. url.PathEscape(DBUser), url.PathEscape(DBPasswd), host, port, DBName, DBParam, DBSSLMode)
  175. }
  176. return
  177. }
  178. // ParseMSSQLHostPort splits the host into host and port
  179. func ParseMSSQLHostPort(info string) (string, string) {
  180. host, port := "127.0.0.1", "1433"
  181. if strings.Contains(info, ":") {
  182. host = strings.Split(info, ":")[0]
  183. port = strings.Split(info, ":")[1]
  184. } else if strings.Contains(info, ",") {
  185. host = strings.Split(info, ",")[0]
  186. port = strings.TrimSpace(strings.Split(info, ",")[1])
  187. } else if len(info) > 0 {
  188. host = info
  189. }
  190. return host, port
  191. }
  192. func getEngine() (*xorm.Engine, error) {
  193. connStr := ""
  194. var Param = "?"
  195. if strings.Contains(DbCfg.Name, Param) {
  196. Param = "&"
  197. }
  198. switch DbCfg.Type {
  199. case "mysql":
  200. connType := "tcp"
  201. if DbCfg.Host[0] == '/' { // looks like a unix socket
  202. connType = "unix"
  203. }
  204. tls := DbCfg.SSLMode
  205. if tls == "disable" { // allow (Postgres-inspired) default value to work in MySQL
  206. tls = "false"
  207. }
  208. connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%scharset=%s&parseTime=true&tls=%s",
  209. DbCfg.User, DbCfg.Passwd, connType, DbCfg.Host, DbCfg.Name, Param, DbCfg.Charset, tls)
  210. case "postgres":
  211. connStr = getPostgreSQLConnectionString(DbCfg.Host, DbCfg.User, DbCfg.Passwd, DbCfg.Name, Param, DbCfg.SSLMode)
  212. case "mssql":
  213. host, port := ParseMSSQLHostPort(DbCfg.Host)
  214. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  215. case "sqlite3":
  216. if !EnableSQLite3 {
  217. return nil, errors.New("this binary version does not build support for SQLite3")
  218. }
  219. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  220. return nil, fmt.Errorf("Failed to create directories: %v", err)
  221. }
  222. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", DbCfg.Path, DbCfg.Timeout)
  223. case "tidb":
  224. if !EnableTiDB {
  225. return nil, errors.New("this binary version does not build support for TiDB")
  226. }
  227. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  228. return nil, fmt.Errorf("Failed to create directories: %v", err)
  229. }
  230. connStr = "goleveldb://" + DbCfg.Path
  231. default:
  232. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  233. }
  234. return xorm.NewEngine(DbCfg.Type, connStr)
  235. }
  236. // NewTestEngine sets a new test xorm.Engine
  237. func NewTestEngine(x *xorm.Engine) (err error) {
  238. x, err = getEngine()
  239. if err != nil {
  240. return fmt.Errorf("Connect to database: %v", err)
  241. }
  242. x.SetMapper(core.GonicMapper{})
  243. x.SetLogger(NewXORMLogger(!setting.ProdMode))
  244. x.ShowSQL(!setting.ProdMode)
  245. return x.StoreEngine("InnoDB").Sync2(tables...)
  246. }
  247. // SetEngine sets the xorm.Engine
  248. func SetEngine() (err error) {
  249. x, err = getEngine()
  250. if err != nil {
  251. return fmt.Errorf("Failed to connect to database: %v", err)
  252. }
  253. x.SetMapper(core.GonicMapper{})
  254. // WARNING: for serv command, MUST remove the output to os.stdout,
  255. // so use log file to instead print to stdout.
  256. x.SetLogger(NewXORMLogger(setting.LogSQL))
  257. x.ShowSQL(setting.LogSQL)
  258. if DbCfg.Type == "mysql" {
  259. x.SetMaxIdleConns(0)
  260. x.SetConnMaxLifetime(3 * time.Second)
  261. }
  262. return nil
  263. }
  264. // NewEngine initializes a new xorm.Engine
  265. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  266. if err = SetEngine(); err != nil {
  267. return err
  268. }
  269. if err = x.Ping(); err != nil {
  270. return err
  271. }
  272. if err = migrateFunc(x); err != nil {
  273. return fmt.Errorf("migrate: %v", err)
  274. }
  275. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  276. return fmt.Errorf("sync database struct error: %v", err)
  277. }
  278. return nil
  279. }
  280. // Statistic contains the database statistics
  281. type Statistic struct {
  282. Counter struct {
  283. User, Org, PublicKey,
  284. Repo, Watch, Star, Action, Access,
  285. Issue, Comment, Oauth, Follow,
  286. Mirror, Release, LoginSource, Webhook,
  287. Milestone, Label, HookTask,
  288. Team, UpdateTask, Attachment int64
  289. }
  290. }
  291. // GetStatistic returns the database statistics
  292. func GetStatistic() (stats Statistic) {
  293. stats.Counter.User = CountUsers()
  294. stats.Counter.Org = CountOrganizations()
  295. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  296. stats.Counter.Repo = CountRepositories(true)
  297. stats.Counter.Watch, _ = x.Count(new(Watch))
  298. stats.Counter.Star, _ = x.Count(new(Star))
  299. stats.Counter.Action, _ = x.Count(new(Action))
  300. stats.Counter.Access, _ = x.Count(new(Access))
  301. stats.Counter.Issue, _ = x.Count(new(Issue))
  302. stats.Counter.Comment, _ = x.Count(new(Comment))
  303. stats.Counter.Oauth = 0
  304. stats.Counter.Follow, _ = x.Count(new(Follow))
  305. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  306. stats.Counter.Release, _ = x.Count(new(Release))
  307. stats.Counter.LoginSource = CountLoginSources()
  308. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  309. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  310. stats.Counter.Label, _ = x.Count(new(Label))
  311. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  312. stats.Counter.Team, _ = x.Count(new(Team))
  313. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  314. return
  315. }
  316. // Ping tests if database is alive
  317. func Ping() error {
  318. if x != nil {
  319. return x.Ping()
  320. }
  321. return errors.New("database not configured")
  322. }
  323. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  324. func DumpDatabase(filePath string, dbType string) error {
  325. var tbs []*core.Table
  326. for _, t := range tables {
  327. t := x.TableInfo(t)
  328. t.Table.Name = t.Name
  329. tbs = append(tbs, t.Table)
  330. }
  331. if len(dbType) > 0 {
  332. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  333. }
  334. return x.DumpTablesToFile(tbs, filePath)
  335. }