migrator.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package sqlite
  2. import (
  3. "context"
  4. "embed"
  5. "fmt"
  6. "io/fs"
  7. "os"
  8. "regexp"
  9. "sort"
  10. "time"
  11. "github.com/pkg/errors"
  12. "github.com/usememos/memos/server/version"
  13. "github.com/usememos/memos/store"
  14. )
  15. //go:embed migration
  16. var migrationFS embed.FS
  17. //go:embed seed
  18. var seedFS embed.FS
  19. // Migrate applies the latest schema to the database.
  20. func (d *DB) Migrate(ctx context.Context) error {
  21. currentVersion := version.GetCurrentVersion(d.profile.Mode)
  22. if d.profile.Mode == "prod" {
  23. _, err := os.Stat(d.profile.DSN)
  24. if err != nil {
  25. // If db file not exists, we should create a new one with latest schema.
  26. if errors.Is(err, os.ErrNotExist) {
  27. if err := d.applyLatestSchema(ctx); err != nil {
  28. return errors.Wrap(err, "failed to apply latest schema")
  29. }
  30. // Upsert the newest version to migration_history.
  31. if _, err := d.UpsertMigrationHistory(ctx, &store.UpsertMigrationHistory{
  32. Version: currentVersion,
  33. }); err != nil {
  34. return errors.Wrap(err, "failed to upsert migration history")
  35. }
  36. } else {
  37. return errors.Wrap(err, "failed to get db file stat")
  38. }
  39. } else {
  40. // If db file exists, we should check if we need to migrate the database.
  41. migrationHistoryList, err := d.FindMigrationHistoryList(ctx, &store.FindMigrationHistory{})
  42. if err != nil {
  43. return errors.Wrap(err, "failed to find migration history")
  44. }
  45. // If no migration history, we should apply the latest version migration and upsert the migration history.
  46. if len(migrationHistoryList) == 0 {
  47. minorVersion := version.GetMinorVersion(currentVersion)
  48. if err := d.applyMigrationForMinorVersion(ctx, minorVersion); err != nil {
  49. return errors.Wrapf(err, "failed to apply version %s migration", minorVersion)
  50. }
  51. _, err := d.UpsertMigrationHistory(ctx, &store.UpsertMigrationHistory{
  52. Version: currentVersion,
  53. })
  54. if err != nil {
  55. return errors.Wrap(err, "failed to upsert migration history")
  56. }
  57. return nil
  58. }
  59. migrationHistoryVersionList := []string{}
  60. for _, migrationHistory := range migrationHistoryList {
  61. migrationHistoryVersionList = append(migrationHistoryVersionList, migrationHistory.Version)
  62. }
  63. sort.Sort(version.SortVersion(migrationHistoryVersionList))
  64. latestMigrationHistoryVersion := migrationHistoryVersionList[len(migrationHistoryVersionList)-1]
  65. if version.IsVersionGreaterThan(version.GetSchemaVersion(currentVersion), latestMigrationHistoryVersion) {
  66. minorVersionList := getMinorVersionList()
  67. // Backup the raw database file before migration.
  68. rawBytes, err := os.ReadFile(d.profile.DSN)
  69. if err != nil {
  70. return errors.Wrap(err, "failed to read raw database file")
  71. }
  72. backupDBFilePath := fmt.Sprintf("%s/memos_%s_%d_backup.db", d.profile.Data, d.profile.Version, time.Now().Unix())
  73. if err := os.WriteFile(backupDBFilePath, rawBytes, 0644); err != nil {
  74. return errors.Wrap(err, "failed to write raw database file")
  75. }
  76. fmt.Println("succeed to copy a backup database file")
  77. fmt.Println("start migrate")
  78. for _, minorVersion := range minorVersionList {
  79. normalizedVersion := minorVersion + ".0"
  80. if version.IsVersionGreaterThan(normalizedVersion, latestMigrationHistoryVersion) && version.IsVersionGreaterOrEqualThan(currentVersion, normalizedVersion) {
  81. fmt.Println("applying migration for", normalizedVersion)
  82. if err := d.applyMigrationForMinorVersion(ctx, minorVersion); err != nil {
  83. return errors.Wrap(err, "failed to apply minor version migration")
  84. }
  85. }
  86. }
  87. fmt.Println("end migrate")
  88. // Remove the created backup db file after migrate succeed.
  89. if err := os.Remove(backupDBFilePath); err != nil {
  90. fmt.Printf("Failed to remove temp database file, err %v", err)
  91. }
  92. }
  93. }
  94. } else {
  95. // In non-prod mode, we should always migrate the database.
  96. if _, err := os.Stat(d.profile.DSN); errors.Is(err, os.ErrNotExist) {
  97. if err := d.applyLatestSchema(ctx); err != nil {
  98. return errors.Wrap(err, "failed to apply latest schema")
  99. }
  100. // In demo mode, we should seed the database.
  101. if d.profile.Mode == "demo" {
  102. if err := d.seed(ctx); err != nil {
  103. return errors.Wrap(err, "failed to seed")
  104. }
  105. }
  106. }
  107. }
  108. return nil
  109. }
  110. const (
  111. latestSchemaFileName = "LATEST__SCHEMA.sql"
  112. )
  113. func (d *DB) applyLatestSchema(ctx context.Context) error {
  114. schemaMode := "dev"
  115. if d.profile.Mode == "prod" {
  116. schemaMode = "prod"
  117. }
  118. latestSchemaPath := fmt.Sprintf("migration/%s/%s", schemaMode, latestSchemaFileName)
  119. buf, err := migrationFS.ReadFile(latestSchemaPath)
  120. if err != nil {
  121. return errors.Wrapf(err, "failed to read latest schema %q", latestSchemaPath)
  122. }
  123. stmt := string(buf)
  124. if err := d.execute(ctx, stmt); err != nil {
  125. return errors.Wrapf(err, "migrate error: %s", stmt)
  126. }
  127. return nil
  128. }
  129. func (d *DB) applyMigrationForMinorVersion(ctx context.Context, minorVersion string) error {
  130. filenames, err := fs.Glob(migrationFS, fmt.Sprintf("%s/%s/*.sql", "migration/prod", minorVersion))
  131. if err != nil {
  132. return errors.Wrap(err, "failed to read ddl files")
  133. }
  134. sort.Strings(filenames)
  135. migrationStmt := ""
  136. // Loop over all migration files and execute them in order.
  137. for _, filename := range filenames {
  138. buf, err := migrationFS.ReadFile(filename)
  139. if err != nil {
  140. return errors.Wrapf(err, "failed to read minor version migration file, filename=%s", filename)
  141. }
  142. stmt := string(buf)
  143. migrationStmt += stmt
  144. if err := d.execute(ctx, stmt); err != nil {
  145. return errors.Wrapf(err, "migrate error: %s", stmt)
  146. }
  147. }
  148. // Upsert the newest version to migration_history.
  149. version := minorVersion + ".0"
  150. if _, err = d.UpsertMigrationHistory(ctx, &store.UpsertMigrationHistory{
  151. Version: version,
  152. }); err != nil {
  153. return errors.Wrapf(err, "failed to upsert migration history with version: %s", version)
  154. }
  155. return nil
  156. }
  157. func (d *DB) seed(ctx context.Context) error {
  158. filenames, err := fs.Glob(seedFS, fmt.Sprintf("%s/*.sql", "seed"))
  159. if err != nil {
  160. return errors.Wrap(err, "failed to read seed files")
  161. }
  162. sort.Strings(filenames)
  163. // Loop over all seed files and execute them in order.
  164. for _, filename := range filenames {
  165. buf, err := seedFS.ReadFile(filename)
  166. if err != nil {
  167. return errors.Wrapf(err, "failed to read seed file, filename=%s", filename)
  168. }
  169. stmt := string(buf)
  170. if err := d.execute(ctx, stmt); err != nil {
  171. return errors.Wrapf(err, "seed error: %s", stmt)
  172. }
  173. }
  174. return nil
  175. }
  176. // execute runs a single SQL statement within a transaction.
  177. func (d *DB) execute(ctx context.Context, stmt string) error {
  178. tx, err := d.db.Begin()
  179. if err != nil {
  180. return err
  181. }
  182. defer tx.Rollback()
  183. if _, err := tx.ExecContext(ctx, stmt); err != nil {
  184. return errors.Wrap(err, "failed to execute statement")
  185. }
  186. return tx.Commit()
  187. }
  188. // minorDirRegexp is a regular expression for minor version directory.
  189. var minorDirRegexp = regexp.MustCompile(`^migration/prod/[0-9]+\.[0-9]+$`)
  190. func getMinorVersionList() []string {
  191. minorVersionList := []string{}
  192. if err := fs.WalkDir(migrationFS, "migration", func(path string, file fs.DirEntry, err error) error {
  193. if err != nil {
  194. return err
  195. }
  196. if file.IsDir() && minorDirRegexp.MatchString(path) {
  197. minorVersionList = append(minorVersionList, file.Name())
  198. }
  199. return nil
  200. }); err != nil {
  201. panic(err)
  202. }
  203. sort.Sort(version.SortVersion(minorVersionList))
  204. return minorVersionList
  205. }