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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. "code.gitea.io/gitea/modules/log"
  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 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.Path = sec.Key("PATH").MustString(filepath.Join(setting.AppDataPath, "gitea.db"))
  150. DbCfg.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  151. }
  152. // parsePostgreSQLHostPort parses given input in various forms defined in
  153. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  154. // and returns proper host and port number.
  155. func parsePostgreSQLHostPort(info string) (string, string) {
  156. host, port := "127.0.0.1", "5432"
  157. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  158. idx := strings.LastIndex(info, ":")
  159. host = info[:idx]
  160. port = info[idx+1:]
  161. } else if len(info) > 0 {
  162. host = info
  163. }
  164. return host, port
  165. }
  166. func getPostgreSQLConnectionString(DBHost, DBUser, DBPasswd, DBName, DBParam, DBSSLMode string) (connStr string) {
  167. host, port := parsePostgreSQLHostPort(DBHost)
  168. if host[0] == '/' { // looks like a unix socket
  169. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  170. url.PathEscape(DBUser), url.PathEscape(DBPasswd), port, DBName, DBParam, DBSSLMode, host)
  171. } else {
  172. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  173. url.PathEscape(DBUser), url.PathEscape(DBPasswd), host, port, DBName, DBParam, DBSSLMode)
  174. }
  175. return
  176. }
  177. // ParseMSSQLHostPort splits the host into host and port
  178. func ParseMSSQLHostPort(info string) (string, string) {
  179. host, port := "127.0.0.1", "1433"
  180. if strings.Contains(info, ":") {
  181. host = strings.Split(info, ":")[0]
  182. port = strings.Split(info, ":")[1]
  183. } else if strings.Contains(info, ",") {
  184. host = strings.Split(info, ",")[0]
  185. port = strings.TrimSpace(strings.Split(info, ",")[1])
  186. } else if len(info) > 0 {
  187. host = info
  188. }
  189. return host, port
  190. }
  191. func getEngine() (*xorm.Engine, error) {
  192. connStr := ""
  193. var Param = "?"
  194. if strings.Contains(DbCfg.Name, Param) {
  195. Param = "&"
  196. }
  197. switch DbCfg.Type {
  198. case "mysql":
  199. connType := "tcp"
  200. if DbCfg.Host[0] == '/' { // looks like a unix socket
  201. connType = "unix"
  202. }
  203. tls := DbCfg.SSLMode
  204. if tls == "disable" { // allow (Postgres-inspired) default value to work in MySQL
  205. tls = "false"
  206. }
  207. connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%scharset=utf8&parseTime=true&tls=%s",
  208. DbCfg.User, DbCfg.Passwd, connType, DbCfg.Host, DbCfg.Name, Param, tls)
  209. case "postgres":
  210. connStr = getPostgreSQLConnectionString(DbCfg.Host, DbCfg.User, DbCfg.Passwd, DbCfg.Name, Param, DbCfg.SSLMode)
  211. case "mssql":
  212. host, port := ParseMSSQLHostPort(DbCfg.Host)
  213. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  214. case "sqlite3":
  215. if !EnableSQLite3 {
  216. return nil, errors.New("this binary version does not build support for SQLite3")
  217. }
  218. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  219. return nil, fmt.Errorf("Failed to create directories: %v", err)
  220. }
  221. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", DbCfg.Path, DbCfg.Timeout)
  222. case "tidb":
  223. if !EnableTiDB {
  224. return nil, errors.New("this binary version does not build support for TiDB")
  225. }
  226. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  227. return nil, fmt.Errorf("Failed to create directories: %v", err)
  228. }
  229. connStr = "goleveldb://" + DbCfg.Path
  230. default:
  231. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  232. }
  233. return xorm.NewEngine(DbCfg.Type, connStr)
  234. }
  235. // NewTestEngine sets a new test xorm.Engine
  236. func NewTestEngine(x *xorm.Engine) (err error) {
  237. x, err = getEngine()
  238. if err != nil {
  239. return fmt.Errorf("Connect to database: %v", err)
  240. }
  241. x.SetMapper(core.GonicMapper{})
  242. x.SetLogger(log.XORMLogger)
  243. x.ShowSQL(!setting.ProdMode)
  244. return x.StoreEngine("InnoDB").Sync2(tables...)
  245. }
  246. // SetEngine sets the xorm.Engine
  247. func SetEngine() (err error) {
  248. x, err = getEngine()
  249. if err != nil {
  250. return fmt.Errorf("Failed to connect to database: %v", err)
  251. }
  252. x.SetMapper(core.GonicMapper{})
  253. // WARNING: for serv command, MUST remove the output to os.stdout,
  254. // so use log file to instead print to stdout.
  255. x.SetLogger(log.XORMLogger)
  256. x.ShowSQL(setting.LogSQL)
  257. return nil
  258. }
  259. // NewEngine initializes a new xorm.Engine
  260. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  261. if err = SetEngine(); err != nil {
  262. return err
  263. }
  264. if err = x.Ping(); err != nil {
  265. return err
  266. }
  267. if err = migrateFunc(x); err != nil {
  268. return fmt.Errorf("migrate: %v", err)
  269. }
  270. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  271. return fmt.Errorf("sync database struct error: %v", err)
  272. }
  273. return nil
  274. }
  275. // Statistic contains the database statistics
  276. type Statistic struct {
  277. Counter struct {
  278. User, Org, PublicKey,
  279. Repo, Watch, Star, Action, Access,
  280. Issue, Comment, Oauth, Follow,
  281. Mirror, Release, LoginSource, Webhook,
  282. Milestone, Label, HookTask,
  283. Team, UpdateTask, Attachment int64
  284. }
  285. }
  286. // GetStatistic returns the database statistics
  287. func GetStatistic() (stats Statistic) {
  288. stats.Counter.User = CountUsers()
  289. stats.Counter.Org = CountOrganizations()
  290. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  291. stats.Counter.Repo = CountRepositories(true)
  292. stats.Counter.Watch, _ = x.Count(new(Watch))
  293. stats.Counter.Star, _ = x.Count(new(Star))
  294. stats.Counter.Action, _ = x.Count(new(Action))
  295. stats.Counter.Access, _ = x.Count(new(Access))
  296. stats.Counter.Issue, _ = x.Count(new(Issue))
  297. stats.Counter.Comment, _ = x.Count(new(Comment))
  298. stats.Counter.Oauth = 0
  299. stats.Counter.Follow, _ = x.Count(new(Follow))
  300. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  301. stats.Counter.Release, _ = x.Count(new(Release))
  302. stats.Counter.LoginSource = CountLoginSources()
  303. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  304. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  305. stats.Counter.Label, _ = x.Count(new(Label))
  306. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  307. stats.Counter.Team, _ = x.Count(new(Team))
  308. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  309. return
  310. }
  311. // Ping tests if database is alive
  312. func Ping() error {
  313. if x != nil {
  314. return x.Ping()
  315. }
  316. return errors.New("database not configured")
  317. }
  318. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  319. func DumpDatabase(filePath string, dbType string) error {
  320. var tbs []*core.Table
  321. for _, t := range tables {
  322. t := x.TableInfo(t)
  323. t.Table.Name = t.Name
  324. tbs = append(tbs, t.Table)
  325. }
  326. if len(dbType) > 0 {
  327. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  328. }
  329. return x.DumpTablesToFile(tbs, filePath)
  330. }