models.go 12 KB

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