migrator.go 7.2 KB

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