models.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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() 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) error {
  231. if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
  232. return err
  233. }
  234. // Purposely create a local variable to not modify global variable
  235. tables := append(tables, new(Version))
  236. for _, table := range tables {
  237. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.")
  238. tableFile := path.Join(dirPath, tableName+".json")
  239. f, err := os.Create(tableFile)
  240. if err != nil {
  241. return fmt.Errorf("create JSON file: %v", err)
  242. }
  243. if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
  244. return jsoniter.NewEncoder(f).Encode(bean)
  245. }); err != nil {
  246. _ = f.Close()
  247. return fmt.Errorf("dump table '%s': %v", tableName, err)
  248. }
  249. _ = f.Close()
  250. }
  251. return nil
  252. }
  253. // ImportDatabase imports data from backup archive.
  254. func ImportDatabase(dirPath string, verbose bool) (err error) {
  255. snakeMapper := core.SnakeMapper{}
  256. skipInsertProcessors := map[string]bool{
  257. "mirror": true,
  258. "milestone": true,
  259. }
  260. // Purposely create a local variable to not modify global variable
  261. tables := append(tables, new(Version))
  262. for _, table := range tables {
  263. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.")
  264. tableFile := path.Join(dirPath, tableName+".json")
  265. if !com.IsExist(tableFile) {
  266. continue
  267. }
  268. if verbose {
  269. log.Trace("Importing table '%s'...", tableName)
  270. }
  271. if err = x.DropTables(table); err != nil {
  272. return fmt.Errorf("drop table '%s': %v", tableName, err)
  273. } else if err = x.Sync2(table); err != nil {
  274. return fmt.Errorf("sync table '%s': %v", tableName, err)
  275. }
  276. f, err := os.Open(tableFile)
  277. if err != nil {
  278. return fmt.Errorf("open JSON file: %v", err)
  279. }
  280. rawTableName := x.TableName(table)
  281. _, isInsertProcessor := table.(xorm.BeforeInsertProcessor)
  282. scanner := bufio.NewScanner(f)
  283. for scanner.Scan() {
  284. switch bean := table.(type) {
  285. case *LoginSource:
  286. meta := make(map[string]interface{})
  287. if err = jsoniter.Unmarshal(scanner.Bytes(), &meta); err != nil {
  288. return fmt.Errorf("unmarshal to map: %v", err)
  289. }
  290. tp := LoginType(com.StrTo(com.ToStr(meta["Type"])).MustInt64())
  291. switch tp {
  292. case LOGIN_LDAP, LOGIN_DLDAP:
  293. bean.Cfg = new(LDAPConfig)
  294. case LOGIN_SMTP:
  295. bean.Cfg = new(SMTPConfig)
  296. case LOGIN_PAM:
  297. bean.Cfg = new(PAMConfig)
  298. case LOGIN_GITHUB:
  299. bean.Cfg = new(GitHubConfig)
  300. default:
  301. return fmt.Errorf("unrecognized login source type:: %v", tp)
  302. }
  303. table = bean
  304. }
  305. if err = jsoniter.Unmarshal(scanner.Bytes(), table); err != nil {
  306. return fmt.Errorf("unmarshal to struct: %v", err)
  307. }
  308. if _, err = x.Insert(table); err != nil {
  309. return fmt.Errorf("insert strcut: %v", err)
  310. }
  311. meta := make(map[string]interface{})
  312. if err = jsoniter.Unmarshal(scanner.Bytes(), &meta); err != nil {
  313. log.Error("Failed to unmarshal to map: %v", err)
  314. }
  315. // Reset created_unix back to the date save in archive because Insert method updates its value
  316. if isInsertProcessor && !skipInsertProcessors[rawTableName] {
  317. if _, err = x.Exec("UPDATE "+rawTableName+" SET created_unix=? WHERE id=?", meta["CreatedUnix"], meta["ID"]); err != nil {
  318. log.Error("Failed to reset 'created_unix': %v", err)
  319. }
  320. }
  321. switch rawTableName {
  322. case "milestone":
  323. if _, err = x.Exec("UPDATE "+rawTableName+" SET deadline_unix=?, closed_date_unix=? WHERE id=?", meta["DeadlineUnix"], meta["ClosedDateUnix"], meta["ID"]); err != nil {
  324. log.Error("Failed to reset 'milestone.deadline_unix', 'milestone.closed_date_unix': %v", err)
  325. }
  326. }
  327. }
  328. // PostgreSQL needs manually reset table sequence for auto increment keys
  329. if conf.UsePostgreSQL {
  330. rawTableName := snakeMapper.Obj2Table(tableName)
  331. seqName := rawTableName + "_id_seq"
  332. if _, err = x.Exec(fmt.Sprintf(`SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM "%s"), 1), false);`, seqName, rawTableName)); err != nil {
  333. return fmt.Errorf("reset table '%s' sequence: %v", rawTableName, err)
  334. }
  335. }
  336. }
  337. return nil
  338. }