migrations.go 10 KB

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