db.go 7.3 KB

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