models.go 12 KB

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