models.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. "bufio"
  7. "database/sql"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "net/url"
  12. "os"
  13. "path"
  14. "strings"
  15. "github.com/Unknwon/com"
  16. _ "github.com/denisenkom/go-mssqldb"
  17. _ "github.com/go-sql-driver/mysql"
  18. "github.com/go-xorm/core"
  19. "github.com/go-xorm/xorm"
  20. _ "github.com/lib/pq"
  21. "github.com/gogits/gogs/models/migrations"
  22. "github.com/gogits/gogs/modules/setting"
  23. )
  24. // Engine represents a xorm engine or session.
  25. type Engine interface {
  26. Delete(interface{}) (int64, error)
  27. Exec(string, ...interface{}) (sql.Result, error)
  28. Find(interface{}, ...interface{}) error
  29. Get(interface{}) (bool, error)
  30. Id(interface{}) *xorm.Session
  31. In(string, ...interface{}) *xorm.Session
  32. Insert(...interface{}) (int64, error)
  33. InsertOne(interface{}) (int64, error)
  34. Iterate(interface{}, xorm.IterFunc) error
  35. Sql(string, ...interface{}) *xorm.Session
  36. Table(interface{}) *xorm.Session
  37. Where(interface{}, ...interface{}) *xorm.Session
  38. }
  39. func sessionRelease(sess *xorm.Session) {
  40. if !sess.IsCommitedOrRollbacked {
  41. sess.Rollback()
  42. }
  43. sess.Close()
  44. }
  45. var (
  46. x *xorm.Engine
  47. tables []interface{}
  48. HasEngine bool
  49. DbCfg struct {
  50. Type, Host, Name, User, Passwd, Path, SSLMode string
  51. }
  52. EnableSQLite3 bool
  53. )
  54. func init() {
  55. tables = append(tables,
  56. new(User), new(PublicKey), new(AccessToken),
  57. new(Repository), new(DeployKey), new(Collaboration), new(Access), new(Upload),
  58. new(Watch), new(Star), new(Follow), new(Action),
  59. new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
  60. new(Label), new(IssueLabel), new(Milestone),
  61. new(Mirror), new(Release), new(LoginSource), new(Webhook), new(HookTask),
  62. new(ProtectBranch), new(ProtectBranchWhitelist),
  63. new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
  64. new(Notice), new(EmailAddress))
  65. gonicNames := []string{"SSL"}
  66. for _, name := range gonicNames {
  67. core.LintGonicMapper[name] = true
  68. }
  69. }
  70. func LoadConfigs() {
  71. sec := setting.Cfg.Section("database")
  72. DbCfg.Type = sec.Key("DB_TYPE").String()
  73. switch DbCfg.Type {
  74. case "sqlite3":
  75. setting.UseSQLite3 = true
  76. case "mysql":
  77. setting.UseMySQL = true
  78. case "postgres":
  79. setting.UsePostgreSQL = true
  80. case "mssql":
  81. setting.UseMSSQL = true
  82. }
  83. DbCfg.Host = sec.Key("HOST").String()
  84. DbCfg.Name = sec.Key("NAME").String()
  85. DbCfg.User = sec.Key("USER").String()
  86. if len(DbCfg.Passwd) == 0 {
  87. DbCfg.Passwd = sec.Key("PASSWD").String()
  88. }
  89. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  90. DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
  91. }
  92. // parsePostgreSQLHostPort parses given input in various forms defined in
  93. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  94. // and returns proper host and port number.
  95. func parsePostgreSQLHostPort(info string) (string, string) {
  96. host, port := "127.0.0.1", "5432"
  97. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  98. idx := strings.LastIndex(info, ":")
  99. host = info[:idx]
  100. port = info[idx+1:]
  101. } else if len(info) > 0 {
  102. host = info
  103. }
  104. return host, port
  105. }
  106. func parseMSSQLHostPort(info string) (string, string) {
  107. host, port := "127.0.0.1", "1433"
  108. if strings.Contains(info, ":") {
  109. host = strings.Split(info, ":")[0]
  110. port = strings.Split(info, ":")[1]
  111. } else if strings.Contains(info, ",") {
  112. host = strings.Split(info, ",")[0]
  113. port = strings.TrimSpace(strings.Split(info, ",")[1])
  114. } else if len(info) > 0 {
  115. host = info
  116. }
  117. return host, port
  118. }
  119. func getEngine() (*xorm.Engine, error) {
  120. connStr := ""
  121. var Param string = "?"
  122. if strings.Contains(DbCfg.Name, Param) {
  123. Param = "&"
  124. }
  125. switch DbCfg.Type {
  126. case "mysql":
  127. if DbCfg.Host[0] == '/' { // looks like a unix socket
  128. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  129. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  130. } else {
  131. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  132. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  133. }
  134. case "postgres":
  135. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  136. if host[0] == '/' { // looks like a unix socket
  137. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  138. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  139. } else {
  140. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  141. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  142. }
  143. case "mssql":
  144. host, port := parseMSSQLHostPort(DbCfg.Host)
  145. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  146. case "sqlite3":
  147. if !EnableSQLite3 {
  148. return nil, errors.New("This binary version does not build support for SQLite3.")
  149. }
  150. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  151. return nil, fmt.Errorf("Fail to create directories: %v", err)
  152. }
  153. connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  154. default:
  155. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  156. }
  157. return xorm.NewEngine(DbCfg.Type, connStr)
  158. }
  159. func NewTestEngine(x *xorm.Engine) (err error) {
  160. x, err = getEngine()
  161. if err != nil {
  162. return fmt.Errorf("Connect to database: %v", err)
  163. }
  164. x.SetMapper(core.GonicMapper{})
  165. return x.StoreEngine("InnoDB").Sync2(tables...)
  166. }
  167. func SetEngine() (err error) {
  168. x, err = getEngine()
  169. if err != nil {
  170. return fmt.Errorf("Fail to connect to database: %v", err)
  171. }
  172. x.SetMapper(core.GonicMapper{})
  173. // WARNING: for serv command, MUST remove the output to os.stdout,
  174. // so use log file to instead print to stdout.
  175. logPath := path.Join(setting.LogRootPath, "xorm.log")
  176. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  177. f, err := os.Create(logPath)
  178. if err != nil {
  179. return fmt.Errorf("Fail to create xorm.log: %v", err)
  180. }
  181. if setting.ProdMode {
  182. x.SetLogger(xorm.NewSimpleLogger3(f, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  183. } else {
  184. x.SetLogger(xorm.NewSimpleLogger(f))
  185. }
  186. x.ShowSQL(true)
  187. return nil
  188. }
  189. func NewEngine() (err error) {
  190. if err = SetEngine(); err != nil {
  191. return err
  192. }
  193. if err = migrations.Migrate(x); err != nil {
  194. return fmt.Errorf("migrate: %v", err)
  195. }
  196. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  197. return fmt.Errorf("sync database struct error: %v\n", err)
  198. }
  199. return nil
  200. }
  201. type Statistic struct {
  202. Counter struct {
  203. User, Org, PublicKey,
  204. Repo, Watch, Star, Action, Access,
  205. Issue, Comment, Oauth, Follow,
  206. Mirror, Release, LoginSource, Webhook,
  207. Milestone, Label, HookTask,
  208. Team, UpdateTask, Attachment int64
  209. }
  210. }
  211. func GetStatistic() (stats Statistic) {
  212. stats.Counter.User = CountUsers()
  213. stats.Counter.Org = CountOrganizations()
  214. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  215. stats.Counter.Repo = CountRepositories(true)
  216. stats.Counter.Watch, _ = x.Count(new(Watch))
  217. stats.Counter.Star, _ = x.Count(new(Star))
  218. stats.Counter.Action, _ = x.Count(new(Action))
  219. stats.Counter.Access, _ = x.Count(new(Access))
  220. stats.Counter.Issue, _ = x.Count(new(Issue))
  221. stats.Counter.Comment, _ = x.Count(new(Comment))
  222. stats.Counter.Oauth = 0
  223. stats.Counter.Follow, _ = x.Count(new(Follow))
  224. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  225. stats.Counter.Release, _ = x.Count(new(Release))
  226. stats.Counter.LoginSource = CountLoginSources()
  227. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  228. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  229. stats.Counter.Label, _ = x.Count(new(Label))
  230. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  231. stats.Counter.Team, _ = x.Count(new(Team))
  232. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  233. return
  234. }
  235. func Ping() error {
  236. return x.Ping()
  237. }
  238. // The version table. Should have only one row with id==1
  239. type Version struct {
  240. ID int64
  241. Version int64
  242. }
  243. // DumpDatabase dumps all data from database to file system in JSON format.
  244. func DumpDatabase(dirPath string) (err error) {
  245. os.MkdirAll(dirPath, os.ModePerm)
  246. // Purposely create a local variable to not modify global variable
  247. tables := append(tables, new(Version))
  248. for _, table := range tables {
  249. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  250. tableFile := path.Join(dirPath, tableName+".json")
  251. f, err := os.Create(tableFile)
  252. if err != nil {
  253. return fmt.Errorf("fail to create JSON file: %v", err)
  254. }
  255. if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
  256. enc := json.NewEncoder(f)
  257. return enc.Encode(bean)
  258. }); err != nil {
  259. f.Close()
  260. return fmt.Errorf("fail to dump table '%s': %v", tableName, err)
  261. }
  262. f.Close()
  263. }
  264. return nil
  265. }
  266. // ImportDatabase imports data from backup archive.
  267. func ImportDatabase(dirPath string) (err error) {
  268. // Purposely create a local variable to not modify global variable
  269. tables := append(tables, new(Version))
  270. for _, table := range tables {
  271. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  272. tableFile := path.Join(dirPath, tableName+".json")
  273. if !com.IsExist(tableFile) {
  274. continue
  275. }
  276. if err = x.DropTables(table); err != nil {
  277. return fmt.Errorf("fail to drop table '%s': %v", tableName, err)
  278. } else if err = x.Sync2(table); err != nil {
  279. return fmt.Errorf("fail to sync table '%s': %v", tableName, err)
  280. }
  281. f, err := os.Open(tableFile)
  282. if err != nil {
  283. return fmt.Errorf("fail to open JSON file: %v", err)
  284. }
  285. scanner := bufio.NewScanner(f)
  286. for scanner.Scan() {
  287. switch bean := table.(type) {
  288. case *LoginSource:
  289. meta := make(map[string]interface{})
  290. if err = json.Unmarshal(scanner.Bytes(), &meta); err != nil {
  291. return fmt.Errorf("fail to unmarshal to map: %v", err)
  292. }
  293. tp := LoginType(com.StrTo(com.ToStr(meta["Type"])).MustInt64())
  294. switch tp {
  295. case LOGIN_LDAP, LOGIN_DLDAP:
  296. bean.Cfg = new(LDAPConfig)
  297. case LOGIN_SMTP:
  298. bean.Cfg = new(SMTPConfig)
  299. case LOGIN_PAM:
  300. bean.Cfg = new(PAMConfig)
  301. default:
  302. return fmt.Errorf("unrecognized login source type:: %v", tp)
  303. }
  304. table = bean
  305. }
  306. if err = json.Unmarshal(scanner.Bytes(), table); err != nil {
  307. return fmt.Errorf("fail to unmarshal to struct: %v", err)
  308. }
  309. if _, err = x.Insert(table); err != nil {
  310. return fmt.Errorf("fail to insert strcut: %v", err)
  311. }
  312. }
  313. }
  314. return nil
  315. }