memos/store/sqlite/migrator.go

225 lines
6.6 KiB
Go
Raw Normal View History

package sqlite
2022-02-03 15:32:03 +08:00
import (
"context"
2022-02-03 15:32:03 +08:00
"embed"
"fmt"
"io/fs"
2022-05-01 11:06:29 +08:00
"os"
"regexp"
2022-02-03 15:32:03 +08:00
"sort"
2022-07-22 23:21:12 +08:00
"time"
2022-02-03 15:32:03 +08:00
2023-09-17 22:55:13 +08:00
"github.com/pkg/errors"
"github.com/usememos/memos/server/version"
2022-02-03 15:32:03 +08:00
)
2022-03-28 23:38:12 +08:00
//go:embed migration
var migrationFS embed.FS
2022-02-03 15:32:03 +08:00
//go:embed seed
var seedFS embed.FS
2023-08-26 07:33:45 +08:00
// Migrate applies the latest schema to the database.
func (d *Driver) Migrate(ctx context.Context) error {
if d.profile.Mode == "prod" {
_, err := os.Stat(d.profile.DSN)
2022-11-27 08:52:43 +08:00
if err != nil {
// If db file not exists, we should create a new one with latest schema.
if errors.Is(err, os.ErrNotExist) {
if err := d.applyLatestSchema(ctx); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to apply latest schema")
}
} else {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to get db file stat")
}
} else {
// If db file exists, we should check if we need to migrate the database.
currentVersion := version.GetCurrentVersion(d.profile.Mode)
migrationHistoryList, err := d.FindMigrationHistoryList(ctx, &MigrationHistoryFind{})
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to find migration history")
}
if len(migrationHistoryList) == 0 {
_, err := d.UpsertMigrationHistory(ctx, &MigrationHistoryUpsert{
Version: currentVersion,
})
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to upsert migration history")
}
return nil
2022-11-27 08:52:43 +08:00
}
migrationHistoryVersionList := []string{}
for _, migrationHistory := range migrationHistoryList {
migrationHistoryVersionList = append(migrationHistoryVersionList, migrationHistory.Version)
}
sort.Sort(version.SortVersion(migrationHistoryVersionList))
latestMigrationHistoryVersion := migrationHistoryVersionList[len(migrationHistoryVersionList)-1]
2022-07-22 23:21:12 +08:00
if version.IsVersionGreaterThan(version.GetSchemaVersion(currentVersion), latestMigrationHistoryVersion) {
minorVersionList := getMinorVersionList()
2022-07-22 23:21:12 +08:00
// backup the raw database file before migration
rawBytes, err := os.ReadFile(d.profile.DSN)
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to read raw database file")
}
backupDBFilePath := fmt.Sprintf("%s/memos_%s_%d_backup.db", d.profile.Data, d.profile.Version, time.Now().Unix())
if err := os.WriteFile(backupDBFilePath, rawBytes, 0644); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to write raw database file")
}
println("succeed to copy a backup database file")
println("start migrate")
for _, minorVersion := range minorVersionList {
normalizedVersion := minorVersion + ".0"
if version.IsVersionGreaterThan(normalizedVersion, latestMigrationHistoryVersion) && version.IsVersionGreaterOrEqualThan(currentVersion, normalizedVersion) {
println("applying migration for", normalizedVersion)
if err := d.applyMigrationForMinorVersion(ctx, minorVersion); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to apply minor version migration")
}
}
}
println("end migrate")
2022-07-22 23:21:12 +08:00
// remove the created backup db file after migrate succeed
if err := os.Remove(backupDBFilePath); err != nil {
println(fmt.Sprintf("Failed to remove temp database file, err %v", err))
}
2022-05-01 11:06:29 +08:00
}
}
} else {
2023-02-19 16:34:15 +08:00
// In non-prod mode, we should always migrate the database.
if _, err := os.Stat(d.profile.DSN); errors.Is(err, os.ErrNotExist) {
if err := d.applyLatestSchema(ctx); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to apply latest schema")
}
// In demo mode, we should seed the database.
if d.profile.Mode == "demo" {
if err := d.seed(ctx); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to seed")
}
}
}
2022-02-03 15:32:03 +08:00
}
return nil
}
const (
latestSchemaFileName = "LATEST__SCHEMA.sql"
)
func (d *Driver) applyLatestSchema(ctx context.Context) error {
2023-02-19 16:34:15 +08:00
schemaMode := "dev"
if d.profile.Mode == "prod" {
2023-02-19 16:34:15 +08:00
schemaMode = "prod"
}
2023-09-29 12:47:49 +08:00
latestSchemaPath := fmt.Sprintf("migration/%s/%s", schemaMode, latestSchemaFileName)
buf, err := migrationFS.ReadFile(latestSchemaPath)
2022-05-22 00:59:22 +08:00
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrapf(err, "failed to read latest schema %q", latestSchemaPath)
2022-05-22 00:59:22 +08:00
}
stmt := string(buf)
if err := d.execute(ctx, stmt); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrapf(err, "migrate error: %s", stmt)
}
return nil
}
func (d *Driver) applyMigrationForMinorVersion(ctx context.Context, minorVersion string) error {
2022-07-25 21:17:46 +08:00
filenames, err := fs.Glob(migrationFS, fmt.Sprintf("%s/%s/*.sql", "migration/prod", minorVersion))
2022-03-28 23:38:12 +08:00
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to read ddl files")
2022-03-28 23:38:12 +08:00
}
sort.Strings(filenames)
migrationStmt := ""
2022-03-28 23:38:12 +08:00
// Loop over all migration files and execute them in order.
for _, filename := range filenames {
buf, err := migrationFS.ReadFile(filename)
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrapf(err, "failed to read minor version migration file, filename=%s", filename)
}
stmt := string(buf)
migrationStmt += stmt
if err := d.execute(ctx, stmt); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrapf(err, "migrate error: %s", stmt)
2022-03-28 23:38:12 +08:00
}
}
// Upsert the newest version to migration_history.
2022-11-27 08:52:43 +08:00
version := minorVersion + ".0"
if _, err = d.UpsertMigrationHistory(ctx, &MigrationHistoryUpsert{
2022-11-27 08:52:43 +08:00
Version: version,
}); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrapf(err, "failed to upsert migration history with version: %s", version)
}
return nil
2022-03-28 23:38:12 +08:00
}
func (d *Driver) seed(ctx context.Context) error {
2022-02-03 15:32:03 +08:00
filenames, err := fs.Glob(seedFS, fmt.Sprintf("%s/*.sql", "seed"))
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to read seed files")
2022-02-03 15:32:03 +08:00
}
sort.Strings(filenames)
// Loop over all seed files and execute them in order.
for _, filename := range filenames {
buf, err := seedFS.ReadFile(filename)
if err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrapf(err, "failed to read seed file, filename=%s", filename)
}
stmt := string(buf)
if err := d.execute(ctx, stmt); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrapf(err, "seed error: %s", stmt)
2022-02-03 15:32:03 +08:00
}
}
return nil
}
2022-08-24 21:53:12 +08:00
// execute runs a single SQL statement within a transaction.
func (d *Driver) execute(ctx context.Context, stmt string) error {
tx, err := d.db.Begin()
2022-02-03 15:32:03 +08:00
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, stmt); err != nil {
2023-09-17 22:55:13 +08:00
return errors.Wrap(err, "failed to execute statement")
}
2022-08-24 21:53:12 +08:00
return tx.Commit()
2022-02-03 15:32:03 +08:00
}
// minorDirRegexp is a regular expression for minor version directory.
2022-07-25 21:17:46 +08:00
var minorDirRegexp = regexp.MustCompile(`^migration/prod/[0-9]+\.[0-9]+$`)
func getMinorVersionList() []string {
minorVersionList := []string{}
if err := fs.WalkDir(migrationFS, "migration", func(path string, file fs.DirEntry, err error) error {
if err != nil {
2022-07-01 20:08:25 +08:00
return err
}
if file.IsDir() && minorDirRegexp.MatchString(path) {
minorVersionList = append(minorVersionList, file.Name())
}
2022-02-03 15:32:03 +08:00
return nil
}); err != nil {
panic(err)
2022-07-02 01:06:28 +08:00
}
sort.Sort(version.SortVersion(minorVersionList))
return minorVersionList
}