2024-02-21 23:43:18 +08:00
|
|
|
package store
|
2024-08-16 08:07:30 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-08-26 08:41:26 +08:00
|
|
|
"database/sql"
|
2024-08-16 08:07:30 +08:00
|
|
|
"embed"
|
|
|
|
"fmt"
|
|
|
|
"io/fs"
|
|
|
|
"log/slog"
|
2024-08-26 08:41:26 +08:00
|
|
|
"path/filepath"
|
2024-08-16 08:07:30 +08:00
|
|
|
"sort"
|
2024-08-26 08:41:26 +08:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2024-08-16 08:07:30 +08:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2024-08-16 08:12:09 +08:00
|
|
|
|
2024-08-16 08:07:30 +08:00
|
|
|
"github.com/usememos/memos/server/version"
|
|
|
|
)
|
|
|
|
|
2024-08-26 22:50:46 +08:00
|
|
|
//go:embed migration
|
|
|
|
var migrationFS embed.FS
|
|
|
|
|
|
|
|
//go:embed seed
|
|
|
|
var seedFS embed.FS
|
|
|
|
|
2024-08-26 08:41:26 +08:00
|
|
|
const (
|
2024-08-26 08:47:29 +08:00
|
|
|
// MigrateFileNameSplit is the split character between the patch version and the description in the migration file name.
|
2024-08-26 08:41:26 +08:00
|
|
|
// For example, "1__create_table.sql".
|
2024-08-26 08:47:29 +08:00
|
|
|
MigrateFileNameSplit = "__"
|
|
|
|
// LatestSchemaFileName is the name of the latest schema file.
|
2024-08-26 08:41:26 +08:00
|
|
|
// This file is used to apply the latest schema when no migration history is found.
|
2024-08-26 08:59:35 +08:00
|
|
|
LatestSchemaFileName = "LATEST_SCHEMA.sql"
|
2024-08-26 08:41:26 +08:00
|
|
|
)
|
|
|
|
|
2024-08-16 08:07:30 +08:00
|
|
|
// Migrate applies the latest schema to the database.
|
|
|
|
func (s *Store) Migrate(ctx context.Context) error {
|
|
|
|
if err := s.preMigrate(ctx); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to pre-migrate")
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Profile.Mode == "prod" {
|
|
|
|
migrationHistoryList, err := s.driver.FindMigrationHistoryList(ctx, &FindMigrationHistory{})
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to find migration history")
|
|
|
|
}
|
|
|
|
if len(migrationHistoryList) == 0 {
|
|
|
|
return errors.Errorf("no migration history found")
|
|
|
|
}
|
|
|
|
|
|
|
|
migrationHistoryVersions := []string{}
|
|
|
|
for _, migrationHistory := range migrationHistoryList {
|
|
|
|
migrationHistoryVersions = append(migrationHistoryVersions, migrationHistory.Version)
|
|
|
|
}
|
|
|
|
sort.Sort(version.SortVersion(migrationHistoryVersions))
|
|
|
|
latestMigrationHistoryVersion := migrationHistoryVersions[len(migrationHistoryVersions)-1]
|
2024-08-26 08:41:26 +08:00
|
|
|
schemaVersion, err := s.GetCurrentSchemaVersion()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to get current schema version")
|
|
|
|
}
|
|
|
|
|
|
|
|
if version.IsVersionGreaterThan(schemaVersion, latestMigrationHistoryVersion) {
|
2024-08-29 20:40:50 +08:00
|
|
|
filePaths, err := fs.Glob(migrationFS, fmt.Sprintf("%s*/*.sql", s.getMigrationBasePath()))
|
2024-08-26 08:41:26 +08:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to read migration files")
|
|
|
|
}
|
|
|
|
sort.Strings(filePaths)
|
|
|
|
|
|
|
|
// Start a transaction to apply the latest schema.
|
|
|
|
tx, err := s.driver.GetDB().Begin()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to start transaction")
|
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
2024-08-16 08:07:30 +08:00
|
|
|
|
2024-08-28 22:53:57 +08:00
|
|
|
slog.Info("start migration", slog.String("currentSchemaVersion", latestMigrationHistoryVersion), slog.String("targetSchemaVersion", schemaVersion))
|
2024-08-26 08:41:26 +08:00
|
|
|
for _, filePath := range filePaths {
|
|
|
|
fileSchemaVersion, err := s.getSchemaVersionOfMigrateScript(filePath)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to get schema version of migrate script")
|
|
|
|
}
|
|
|
|
if version.IsVersionGreaterThan(fileSchemaVersion, latestMigrationHistoryVersion) && version.IsVersionGreaterOrEqualThan(schemaVersion, fileSchemaVersion) {
|
|
|
|
bytes, err := migrationFS.ReadFile(filePath)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to read minor version migration file: %s", filePath)
|
|
|
|
}
|
|
|
|
stmt := string(bytes)
|
|
|
|
if err := s.execute(ctx, tx, stmt); err != nil {
|
|
|
|
return errors.Wrapf(err, "migrate error: %s", stmt)
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to commit transaction")
|
|
|
|
}
|
2024-08-28 22:53:57 +08:00
|
|
|
slog.Info("end migrate")
|
2024-08-26 08:41:26 +08:00
|
|
|
|
|
|
|
// Upsert the current schema version to migration_history.
|
|
|
|
if _, err = s.driver.UpsertMigrationHistory(ctx, &UpsertMigrationHistory{
|
|
|
|
Version: schemaVersion,
|
|
|
|
}); err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to upsert migration history with version: %s", schemaVersion)
|
|
|
|
}
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
2024-08-16 08:15:59 +08:00
|
|
|
} else if s.Profile.Mode == "demo" {
|
2024-08-16 08:07:30 +08:00
|
|
|
// In demo mode, we should seed the database.
|
2024-08-16 08:15:59 +08:00
|
|
|
if err := s.seed(ctx); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to seed")
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Store) preMigrate(ctx context.Context) error {
|
|
|
|
migrationHistoryList, err := s.driver.FindMigrationHistoryList(ctx, &FindMigrationHistory{})
|
2024-08-26 08:41:26 +08:00
|
|
|
// If any error occurs or no migration history found, apply the latest schema.
|
2024-08-16 08:07:30 +08:00
|
|
|
if err != nil || len(migrationHistoryList) == 0 {
|
|
|
|
if err != nil {
|
2024-08-26 08:41:26 +08:00
|
|
|
slog.Warn("failed to find migration history in pre-migrate", slog.String("error", err.Error()))
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
2024-08-26 08:47:29 +08:00
|
|
|
filePath := s.getMigrationBasePath() + LatestSchemaFileName
|
2024-08-26 08:41:26 +08:00
|
|
|
bytes, err := migrationFS.ReadFile(filePath)
|
2024-08-16 08:07:30 +08:00
|
|
|
if err != nil {
|
|
|
|
return errors.Errorf("failed to read latest schema file: %s", err)
|
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
schemaVersion, err := s.GetCurrentSchemaVersion()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to get current schema version")
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
|
|
|
|
// Start a transaction to apply the latest schema.
|
|
|
|
tx, err := s.driver.GetDB().Begin()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to start transaction")
|
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
|
|
|
if err := s.execute(ctx, tx, string(bytes)); err != nil {
|
|
|
|
return errors.Errorf("failed to execute SQL file %s, err %s", filePath, err)
|
|
|
|
}
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to commit transaction")
|
|
|
|
}
|
|
|
|
|
2024-08-16 08:07:30 +08:00
|
|
|
if _, err := s.driver.UpsertMigrationHistory(ctx, &UpsertMigrationHistory{
|
2024-08-26 08:41:26 +08:00
|
|
|
Version: schemaVersion,
|
2024-08-16 08:07:30 +08:00
|
|
|
}); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to upsert migration history")
|
|
|
|
}
|
|
|
|
}
|
2024-08-27 09:20:23 +08:00
|
|
|
if s.Profile.Mode == "prod" {
|
|
|
|
if err := s.normalizedMigrationHistoryList(ctx); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to normalize migration history list")
|
|
|
|
}
|
2024-08-26 22:50:46 +08:00
|
|
|
}
|
2024-08-16 08:07:30 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Store) getMigrationBasePath() string {
|
|
|
|
mode := "dev"
|
|
|
|
if s.Profile.Mode == "prod" {
|
|
|
|
mode = "prod"
|
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
return fmt.Sprintf("migration/%s/%s/", s.Profile.Driver, mode)
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Store) getSeedBasePath() string {
|
2024-08-26 08:41:26 +08:00
|
|
|
return fmt.Sprintf("seed/%s/", s.Profile.Driver)
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Store) seed(ctx context.Context) error {
|
|
|
|
// Only seed for SQLite.
|
2024-08-26 08:41:26 +08:00
|
|
|
if s.Profile.Driver != "sqlite" {
|
|
|
|
slog.Warn("seed is only supported for SQLite")
|
2024-08-16 08:07:30 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
filenames, err := fs.Glob(seedFS, fmt.Sprintf("%s*.sql", s.getSeedBasePath()))
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to read seed files")
|
|
|
|
}
|
|
|
|
|
2024-08-26 08:41:26 +08:00
|
|
|
// Sort seed files by name. This is important to ensure that seed files are applied in order.
|
2024-08-16 08:07:30 +08:00
|
|
|
sort.Strings(filenames)
|
2024-08-26 08:41:26 +08:00
|
|
|
// Start a transaction to apply the seed files.
|
|
|
|
tx, err := s.driver.GetDB().Begin()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to start transaction")
|
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
2024-08-16 08:07:30 +08:00
|
|
|
// Loop over all seed files and execute them in order.
|
|
|
|
for _, filename := range filenames {
|
|
|
|
bytes, err := seedFS.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to read seed file, filename=%s", filename)
|
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
if err := s.execute(ctx, tx, string(bytes)); err != nil {
|
2024-08-16 08:07:30 +08:00
|
|
|
return errors.Wrapf(err, "seed error: %s", filename)
|
|
|
|
}
|
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
return tx.Commit()
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
|
|
|
|
2024-08-26 08:41:26 +08:00
|
|
|
func (s *Store) GetCurrentSchemaVersion() (string, error) {
|
|
|
|
currentVersion := version.GetCurrentVersion(s.Profile.Mode)
|
|
|
|
minorVersion := version.GetMinorVersion(currentVersion)
|
|
|
|
filePaths, err := fs.Glob(migrationFS, fmt.Sprintf("%s%s/*.sql", s.getMigrationBasePath(), minorVersion))
|
2024-08-16 08:07:30 +08:00
|
|
|
if err != nil {
|
2024-08-26 08:41:26 +08:00
|
|
|
return "", errors.Wrap(err, "failed to read migration files")
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
|
|
|
|
sort.Strings(filePaths)
|
|
|
|
if len(filePaths) == 0 {
|
|
|
|
return fmt.Sprintf("%s.0", minorVersion), nil
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
2024-08-26 08:47:29 +08:00
|
|
|
return s.getSchemaVersionOfMigrateScript(filePaths[len(filePaths)-1])
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
|
|
|
|
2024-08-26 08:41:26 +08:00
|
|
|
func (s *Store) getSchemaVersionOfMigrateScript(filePath string) (string, error) {
|
|
|
|
// If the file is the latest schema file, return the current schema version.
|
2024-08-26 08:47:29 +08:00
|
|
|
if strings.HasSuffix(filePath, LatestSchemaFileName) {
|
2024-08-26 08:41:26 +08:00
|
|
|
return s.GetCurrentSchemaVersion()
|
|
|
|
}
|
2024-08-16 08:07:30 +08:00
|
|
|
|
2024-08-26 08:41:26 +08:00
|
|
|
normalizedPath := filepath.ToSlash(filePath)
|
|
|
|
elements := strings.Split(normalizedPath, "/")
|
|
|
|
if len(elements) < 2 {
|
|
|
|
return "", errors.Errorf("invalid file path: %s", filePath)
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
2024-08-26 08:41:26 +08:00
|
|
|
minorVersion := elements[len(elements)-2]
|
2024-08-26 08:47:29 +08:00
|
|
|
rawPatchVersion := strings.Split(elements[len(elements)-1], MigrateFileNameSplit)[0]
|
2024-08-26 08:41:26 +08:00
|
|
|
patchVersion, err := strconv.Atoi(rawPatchVersion)
|
|
|
|
if err != nil {
|
|
|
|
return "", errors.Wrapf(err, "failed to convert patch version to int: %s", rawPatchVersion)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s.%d", minorVersion, patchVersion+1), nil
|
|
|
|
}
|
2024-08-16 08:07:30 +08:00
|
|
|
|
2024-08-26 08:41:26 +08:00
|
|
|
// execute runs a single SQL statement within a transaction.
|
2024-08-26 08:47:29 +08:00
|
|
|
func (*Store) execute(ctx context.Context, tx *sql.Tx, stmt string) error {
|
2024-08-26 08:41:26 +08:00
|
|
|
if _, err := tx.ExecContext(ctx, stmt); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to execute statement")
|
|
|
|
}
|
|
|
|
return nil
|
2024-08-16 08:07:30 +08:00
|
|
|
}
|
2024-08-26 22:50:46 +08:00
|
|
|
|
|
|
|
func (s *Store) normalizedMigrationHistoryList(ctx context.Context) error {
|
|
|
|
migrationHistoryList, err := s.driver.FindMigrationHistoryList(ctx, &FindMigrationHistory{})
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to find migration history")
|
|
|
|
}
|
|
|
|
versions := []string{}
|
|
|
|
for _, migrationHistory := range migrationHistoryList {
|
|
|
|
versions = append(versions, migrationHistory.Version)
|
|
|
|
}
|
|
|
|
sort.Sort(version.SortVersion(versions))
|
|
|
|
latestVersion := versions[len(versions)-1]
|
|
|
|
latestMinorVersion := version.GetMinorVersion(latestVersion)
|
2024-08-28 22:53:57 +08:00
|
|
|
|
2024-08-26 22:50:46 +08:00
|
|
|
// If the latest version is greater than 0.22, return.
|
|
|
|
// As of 0.22, the migration history is already normalized.
|
|
|
|
if version.IsVersionGreaterThan(latestMinorVersion, "0.22") {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
schemaVersionMap := map[string]string{}
|
2024-08-29 20:40:50 +08:00
|
|
|
filePaths, err := fs.Glob(migrationFS, fmt.Sprintf("%s*/*.sql", s.getMigrationBasePath()))
|
2024-08-26 22:50:46 +08:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to read migration files")
|
|
|
|
}
|
|
|
|
sort.Strings(filePaths)
|
|
|
|
for _, filePath := range filePaths {
|
|
|
|
fileSchemaVersion, err := s.getSchemaVersionOfMigrateScript(filePath)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to get schema version of migrate script")
|
|
|
|
}
|
2024-08-27 09:20:23 +08:00
|
|
|
schemaVersionMap[version.GetMinorVersion(fileSchemaVersion)] = fileSchemaVersion
|
2024-08-26 22:50:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
latestSchemaVersion := schemaVersionMap[latestMinorVersion]
|
|
|
|
if latestSchemaVersion == "" {
|
|
|
|
return errors.Errorf("latest schema version not found")
|
|
|
|
}
|
|
|
|
if version.IsVersionGreaterOrEqualThan(latestVersion, latestSchemaVersion) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start a transaction to insert the latest schema version to migration_history.
|
|
|
|
tx, err := s.driver.GetDB().Begin()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to start transaction")
|
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
|
|
|
if err := s.execute(ctx, tx, fmt.Sprintf("INSERT INTO migration_history (version) VALUES ('%s')", latestSchemaVersion)); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to insert migration history")
|
|
|
|
}
|
|
|
|
return tx.Commit()
|
|
|
|
}
|