migrations.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // Copyright 2015 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 migrations
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/Unknwon/com"
  10. "github.com/go-xorm/xorm"
  11. log "gopkg.in/clog.v1"
  12. "github.com/gogs/gogs/pkg/tool"
  13. )
  14. const _MIN_DB_VER = 10
  15. type Migration interface {
  16. Description() string
  17. Migrate(*xorm.Engine) error
  18. }
  19. type migration struct {
  20. description string
  21. migrate func(*xorm.Engine) error
  22. }
  23. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  24. return &migration{desc, fn}
  25. }
  26. func (m *migration) Description() string {
  27. return m.description
  28. }
  29. func (m *migration) Migrate(x *xorm.Engine) error {
  30. return m.migrate(x)
  31. }
  32. // The version table. Should have only one row with id==1
  33. type Version struct {
  34. ID int64
  35. Version int64
  36. }
  37. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  38. // If you want to "retire" a migration, remove it from the top of the list and
  39. // update _MIN_VER_DB accordingly
  40. var migrations = []Migration{
  41. // v0 -> v4 : before 0.6.0 -> last support 0.7.33
  42. // v4 -> v10: before 0.7.0 -> last support 0.9.141
  43. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  44. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  45. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  46. // v13 -> v14:v0.9.87
  47. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  48. // v14 -> v15:v0.9.147
  49. NewMigration("generate and migrate Git hooks", generateAndMigrateGitHooks),
  50. // v15 -> v16:v0.10.16
  51. NewMigration("update repository sizes", updateRepositorySizes),
  52. // v16 -> v17:v0.10.31
  53. NewMigration("remove invalid protect branch whitelist", removeInvalidProtectBranchWhitelist),
  54. }
  55. // Migrate database to current version
  56. func Migrate(x *xorm.Engine) error {
  57. if err := x.Sync(new(Version)); err != nil {
  58. return fmt.Errorf("sync: %v", err)
  59. }
  60. currentVersion := &Version{ID: 1}
  61. has, err := x.Get(currentVersion)
  62. if err != nil {
  63. return fmt.Errorf("get: %v", err)
  64. } else if !has {
  65. // If the version record does not exist we think
  66. // it is a fresh installation and we can skip all migrations.
  67. currentVersion.ID = 0
  68. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  69. if _, err = x.InsertOne(currentVersion); err != nil {
  70. return fmt.Errorf("insert: %v", err)
  71. }
  72. }
  73. v := currentVersion.Version
  74. if _MIN_DB_VER > v {
  75. log.Fatal(0, `
  76. Hi there, thank you for using Gogs for so long!
  77. However, Gogs has stopped supporting auto-migration from your previously installed version.
  78. But the good news is, it's very easy to fix this problem!
  79. You can migrate your older database using a previous release, then you can upgrade to the newest version.
  80. Please save following instructions to somewhere and start working:
  81. - If you were using below 0.6.0 (e.g. 0.5.x), download last supported archive from following link:
  82. https://github.com/gogs/gogs/releases/tag/v0.7.33
  83. - If you were using below 0.7.0 (e.g. 0.6.x), download last supported archive from following link:
  84. https://github.com/gogs/gogs/releases/tag/v0.9.141
  85. Once finished downloading,
  86. 1. Extract the archive and to upgrade steps as usual.
  87. 2. Run it once. To verify, you should see some migration traces.
  88. 3. Once it starts web server successfully, stop it.
  89. 4. Now it's time to put back the release archive you originally intent to upgrade.
  90. 5. Enjoy!
  91. In case you're stilling getting this notice, go through instructions again until it disappears.`)
  92. return nil
  93. }
  94. if int(v-_MIN_DB_VER) > len(migrations) {
  95. // User downgraded Gogs.
  96. currentVersion.Version = int64(len(migrations) + _MIN_DB_VER)
  97. _, err = x.Id(1).Update(currentVersion)
  98. return err
  99. }
  100. for i, m := range migrations[v-_MIN_DB_VER:] {
  101. log.Info("Migration: %s", m.Description())
  102. if err = m.Migrate(x); err != nil {
  103. return fmt.Errorf("do migrate: %v", err)
  104. }
  105. currentVersion.Version = v + int64(i) + 1
  106. if _, err = x.Id(1).Update(currentVersion); err != nil {
  107. return err
  108. }
  109. }
  110. return nil
  111. }
  112. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  113. type User struct {
  114. ID int64 `xorm:"pk autoincr"`
  115. Rands string `xorm:"VARCHAR(10)"`
  116. Salt string `xorm:"VARCHAR(10)"`
  117. }
  118. orgs := make([]*User, 0, 10)
  119. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  120. return fmt.Errorf("select all organizations: %v", err)
  121. }
  122. sess := x.NewSession()
  123. defer sess.Close()
  124. if err = sess.Begin(); err != nil {
  125. return err
  126. }
  127. for _, org := range orgs {
  128. if org.Rands, err = tool.RandomString(10); err != nil {
  129. return err
  130. }
  131. if org.Salt, err = tool.RandomString(10); err != nil {
  132. return err
  133. }
  134. if _, err = sess.Id(org.ID).Update(org); err != nil {
  135. return err
  136. }
  137. }
  138. return sess.Commit()
  139. }
  140. type TAction struct {
  141. ID int64 `xorm:"pk autoincr"`
  142. CreatedUnix int64
  143. }
  144. func (t *TAction) TableName() string { return "action" }
  145. type TNotice struct {
  146. ID int64 `xorm:"pk autoincr"`
  147. CreatedUnix int64
  148. }
  149. func (t *TNotice) TableName() string { return "notice" }
  150. type TComment struct {
  151. ID int64 `xorm:"pk autoincr"`
  152. CreatedUnix int64
  153. }
  154. func (t *TComment) TableName() string { return "comment" }
  155. type TIssue struct {
  156. ID int64 `xorm:"pk autoincr"`
  157. DeadlineUnix int64
  158. CreatedUnix int64
  159. UpdatedUnix int64
  160. }
  161. func (t *TIssue) TableName() string { return "issue" }
  162. type TMilestone struct {
  163. ID int64 `xorm:"pk autoincr"`
  164. DeadlineUnix int64
  165. ClosedDateUnix int64
  166. }
  167. func (t *TMilestone) TableName() string { return "milestone" }
  168. type TAttachment struct {
  169. ID int64 `xorm:"pk autoincr"`
  170. CreatedUnix int64
  171. }
  172. func (t *TAttachment) TableName() string { return "attachment" }
  173. type TLoginSource struct {
  174. ID int64 `xorm:"pk autoincr"`
  175. CreatedUnix int64
  176. UpdatedUnix int64
  177. }
  178. func (t *TLoginSource) TableName() string { return "login_source" }
  179. type TPull struct {
  180. ID int64 `xorm:"pk autoincr"`
  181. MergedUnix int64
  182. }
  183. func (t *TPull) TableName() string { return "pull_request" }
  184. type TRelease struct {
  185. ID int64 `xorm:"pk autoincr"`
  186. CreatedUnix int64
  187. }
  188. func (t *TRelease) TableName() string { return "release" }
  189. type TRepo struct {
  190. ID int64 `xorm:"pk autoincr"`
  191. CreatedUnix int64
  192. UpdatedUnix int64
  193. }
  194. func (t *TRepo) TableName() string { return "repository" }
  195. type TMirror struct {
  196. ID int64 `xorm:"pk autoincr"`
  197. UpdatedUnix int64
  198. NextUpdateUnix int64
  199. }
  200. func (t *TMirror) TableName() string { return "mirror" }
  201. type TPublicKey struct {
  202. ID int64 `xorm:"pk autoincr"`
  203. CreatedUnix int64
  204. UpdatedUnix int64
  205. }
  206. func (t *TPublicKey) TableName() string { return "public_key" }
  207. type TDeployKey struct {
  208. ID int64 `xorm:"pk autoincr"`
  209. CreatedUnix int64
  210. UpdatedUnix int64
  211. }
  212. func (t *TDeployKey) TableName() string { return "deploy_key" }
  213. type TAccessToken struct {
  214. ID int64 `xorm:"pk autoincr"`
  215. CreatedUnix int64
  216. UpdatedUnix int64
  217. }
  218. func (t *TAccessToken) TableName() string { return "access_token" }
  219. type TUser struct {
  220. ID int64 `xorm:"pk autoincr"`
  221. CreatedUnix int64
  222. UpdatedUnix int64
  223. }
  224. func (t *TUser) TableName() string { return "user" }
  225. type TWebhook struct {
  226. ID int64 `xorm:"pk autoincr"`
  227. CreatedUnix int64
  228. UpdatedUnix int64
  229. }
  230. func (t *TWebhook) TableName() string { return "webhook" }
  231. func convertDateToUnix(x *xorm.Engine) (err error) {
  232. log.Info("This migration could take up to minutes, please be patient.")
  233. type Bean struct {
  234. ID int64 `xorm:"pk autoincr"`
  235. Created time.Time
  236. Updated time.Time
  237. Merged time.Time
  238. Deadline time.Time
  239. ClosedDate time.Time
  240. NextUpdate time.Time
  241. }
  242. var tables = []struct {
  243. name string
  244. cols []string
  245. bean interface{}
  246. }{
  247. {"action", []string{"created"}, new(TAction)},
  248. {"notice", []string{"created"}, new(TNotice)},
  249. {"comment", []string{"created"}, new(TComment)},
  250. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  251. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  252. {"attachment", []string{"created"}, new(TAttachment)},
  253. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  254. {"pull_request", []string{"merged"}, new(TPull)},
  255. {"release", []string{"created"}, new(TRelease)},
  256. {"repository", []string{"created", "updated"}, new(TRepo)},
  257. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  258. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  259. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  260. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  261. {"user", []string{"created", "updated"}, new(TUser)},
  262. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  263. }
  264. for _, table := range tables {
  265. log.Info("Converting table: %s", table.name)
  266. if err = x.Sync2(table.bean); err != nil {
  267. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  268. }
  269. offset := 0
  270. for {
  271. beans := make([]*Bean, 0, 100)
  272. if err = x.Sql(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d",
  273. table.name, offset)).Find(&beans); err != nil {
  274. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  275. }
  276. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  277. if len(beans) == 0 {
  278. break
  279. }
  280. offset += 100
  281. baseSQL := "UPDATE `" + table.name + "` SET "
  282. for _, bean := range beans {
  283. valSQLs := make([]string, 0, len(table.cols))
  284. for _, col := range table.cols {
  285. fieldSQL := ""
  286. fieldSQL += col + "_unix = "
  287. switch col {
  288. case "deadline":
  289. if bean.Deadline.IsZero() {
  290. continue
  291. }
  292. fieldSQL += com.ToStr(bean.Deadline.Unix())
  293. case "created":
  294. fieldSQL += com.ToStr(bean.Created.Unix())
  295. case "updated":
  296. fieldSQL += com.ToStr(bean.Updated.Unix())
  297. case "closed_date":
  298. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  299. case "merged":
  300. fieldSQL += com.ToStr(bean.Merged.Unix())
  301. case "next_update":
  302. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  303. }
  304. valSQLs = append(valSQLs, fieldSQL)
  305. }
  306. if len(valSQLs) == 0 {
  307. continue
  308. }
  309. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  310. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  311. }
  312. }
  313. }
  314. }
  315. return nil
  316. }