migrations.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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/gogits/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/gogits/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/gogits/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 sessionRelease(sess *xorm.Session) {
  113. if !sess.IsCommitedOrRollbacked {
  114. sess.Rollback()
  115. }
  116. sess.Close()
  117. }
  118. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  119. type User struct {
  120. ID int64 `xorm:"pk autoincr"`
  121. Rands string `xorm:"VARCHAR(10)"`
  122. Salt string `xorm:"VARCHAR(10)"`
  123. }
  124. orgs := make([]*User, 0, 10)
  125. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  126. return fmt.Errorf("select all organizations: %v", err)
  127. }
  128. sess := x.NewSession()
  129. defer sessionRelease(sess)
  130. if err = sess.Begin(); err != nil {
  131. return err
  132. }
  133. for _, org := range orgs {
  134. if org.Rands, err = tool.RandomString(10); err != nil {
  135. return err
  136. }
  137. if org.Salt, err = tool.RandomString(10); err != nil {
  138. return err
  139. }
  140. if _, err = sess.Id(org.ID).Update(org); err != nil {
  141. return err
  142. }
  143. }
  144. return sess.Commit()
  145. }
  146. type TAction struct {
  147. ID int64 `xorm:"pk autoincr"`
  148. CreatedUnix int64
  149. }
  150. func (t *TAction) TableName() string { return "action" }
  151. type TNotice struct {
  152. ID int64 `xorm:"pk autoincr"`
  153. CreatedUnix int64
  154. }
  155. func (t *TNotice) TableName() string { return "notice" }
  156. type TComment struct {
  157. ID int64 `xorm:"pk autoincr"`
  158. CreatedUnix int64
  159. }
  160. func (t *TComment) TableName() string { return "comment" }
  161. type TIssue struct {
  162. ID int64 `xorm:"pk autoincr"`
  163. DeadlineUnix int64
  164. CreatedUnix int64
  165. UpdatedUnix int64
  166. }
  167. func (t *TIssue) TableName() string { return "issue" }
  168. type TMilestone struct {
  169. ID int64 `xorm:"pk autoincr"`
  170. DeadlineUnix int64
  171. ClosedDateUnix int64
  172. }
  173. func (t *TMilestone) TableName() string { return "milestone" }
  174. type TAttachment struct {
  175. ID int64 `xorm:"pk autoincr"`
  176. CreatedUnix int64
  177. }
  178. func (t *TAttachment) TableName() string { return "attachment" }
  179. type TLoginSource struct {
  180. ID int64 `xorm:"pk autoincr"`
  181. CreatedUnix int64
  182. UpdatedUnix int64
  183. }
  184. func (t *TLoginSource) TableName() string { return "login_source" }
  185. type TPull struct {
  186. ID int64 `xorm:"pk autoincr"`
  187. MergedUnix int64
  188. }
  189. func (t *TPull) TableName() string { return "pull_request" }
  190. type TRelease struct {
  191. ID int64 `xorm:"pk autoincr"`
  192. CreatedUnix int64
  193. }
  194. func (t *TRelease) TableName() string { return "release" }
  195. type TRepo struct {
  196. ID int64 `xorm:"pk autoincr"`
  197. CreatedUnix int64
  198. UpdatedUnix int64
  199. }
  200. func (t *TRepo) TableName() string { return "repository" }
  201. type TMirror struct {
  202. ID int64 `xorm:"pk autoincr"`
  203. UpdatedUnix int64
  204. NextUpdateUnix int64
  205. }
  206. func (t *TMirror) TableName() string { return "mirror" }
  207. type TPublicKey struct {
  208. ID int64 `xorm:"pk autoincr"`
  209. CreatedUnix int64
  210. UpdatedUnix int64
  211. }
  212. func (t *TPublicKey) TableName() string { return "public_key" }
  213. type TDeployKey struct {
  214. ID int64 `xorm:"pk autoincr"`
  215. CreatedUnix int64
  216. UpdatedUnix int64
  217. }
  218. func (t *TDeployKey) TableName() string { return "deploy_key" }
  219. type TAccessToken struct {
  220. ID int64 `xorm:"pk autoincr"`
  221. CreatedUnix int64
  222. UpdatedUnix int64
  223. }
  224. func (t *TAccessToken) TableName() string { return "access_token" }
  225. type TUser struct {
  226. ID int64 `xorm:"pk autoincr"`
  227. CreatedUnix int64
  228. UpdatedUnix int64
  229. }
  230. func (t *TUser) TableName() string { return "user" }
  231. type TWebhook struct {
  232. ID int64 `xorm:"pk autoincr"`
  233. CreatedUnix int64
  234. UpdatedUnix int64
  235. }
  236. func (t *TWebhook) TableName() string { return "webhook" }
  237. func convertDateToUnix(x *xorm.Engine) (err error) {
  238. log.Info("This migration could take up to minutes, please be patient.")
  239. type Bean struct {
  240. ID int64 `xorm:"pk autoincr"`
  241. Created time.Time
  242. Updated time.Time
  243. Merged time.Time
  244. Deadline time.Time
  245. ClosedDate time.Time
  246. NextUpdate time.Time
  247. }
  248. var tables = []struct {
  249. name string
  250. cols []string
  251. bean interface{}
  252. }{
  253. {"action", []string{"created"}, new(TAction)},
  254. {"notice", []string{"created"}, new(TNotice)},
  255. {"comment", []string{"created"}, new(TComment)},
  256. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  257. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  258. {"attachment", []string{"created"}, new(TAttachment)},
  259. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  260. {"pull_request", []string{"merged"}, new(TPull)},
  261. {"release", []string{"created"}, new(TRelease)},
  262. {"repository", []string{"created", "updated"}, new(TRepo)},
  263. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  264. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  265. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  266. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  267. {"user", []string{"created", "updated"}, new(TUser)},
  268. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  269. }
  270. for _, table := range tables {
  271. log.Info("Converting table: %s", table.name)
  272. if err = x.Sync2(table.bean); err != nil {
  273. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  274. }
  275. offset := 0
  276. for {
  277. beans := make([]*Bean, 0, 100)
  278. if err = x.Sql(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d",
  279. table.name, offset)).Find(&beans); err != nil {
  280. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  281. }
  282. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  283. if len(beans) == 0 {
  284. break
  285. }
  286. offset += 100
  287. baseSQL := "UPDATE `" + table.name + "` SET "
  288. for _, bean := range beans {
  289. valSQLs := make([]string, 0, len(table.cols))
  290. for _, col := range table.cols {
  291. fieldSQL := ""
  292. fieldSQL += col + "_unix = "
  293. switch col {
  294. case "deadline":
  295. if bean.Deadline.IsZero() {
  296. continue
  297. }
  298. fieldSQL += com.ToStr(bean.Deadline.Unix())
  299. case "created":
  300. fieldSQL += com.ToStr(bean.Created.Unix())
  301. case "updated":
  302. fieldSQL += com.ToStr(bean.Updated.Unix())
  303. case "closed_date":
  304. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  305. case "merged":
  306. fieldSQL += com.ToStr(bean.Merged.Unix())
  307. case "next_update":
  308. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  309. }
  310. valSQLs = append(valSQLs, fieldSQL)
  311. }
  312. if len(valSQLs) == 0 {
  313. continue
  314. }
  315. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  316. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  317. }
  318. }
  319. }
  320. }
  321. return nil
  322. }