2022-05-22 00:59:22 +08:00
|
|
|
package db
|
2022-02-03 15:32:03 +08:00
|
|
|
|
|
|
|
import (
|
2022-08-07 10:17:56 +08:00
|
|
|
"context"
|
2022-02-03 15:32:03 +08:00
|
|
|
"database/sql"
|
|
|
|
"embed"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/fs"
|
2022-05-01 11:06:29 +08:00
|
|
|
"os"
|
2022-07-02 10:47:16 +08:00
|
|
|
"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
|
|
|
|
2022-06-27 22:09:06 +08:00
|
|
|
"github.com/usememos/memos/server/profile"
|
2022-09-12 17:25:34 +08:00
|
|
|
"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
|
|
|
|
|
|
|
|
type DB struct {
|
2022-05-22 09:29:34 +08:00
|
|
|
// sqlite db connection instance
|
2023-01-03 23:05:42 +08:00
|
|
|
DBInstance *sql.DB
|
|
|
|
profile *profile.Profile
|
2022-02-03 15:32:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewDB returns a new instance of DB associated with the given datasource name.
|
2022-05-22 09:29:34 +08:00
|
|
|
func NewDB(profile *profile.Profile) *DB {
|
2022-02-03 15:32:03 +08:00
|
|
|
db := &DB{
|
2022-07-22 23:21:12 +08:00
|
|
|
profile: profile,
|
2022-02-03 15:32:03 +08:00
|
|
|
}
|
|
|
|
return db
|
|
|
|
}
|
|
|
|
|
2023-08-26 07:33:45 +08:00
|
|
|
// Open opens a database specified by its database driver name and a
|
|
|
|
// driver-specific data source name, usually consisting of at least a
|
|
|
|
// database name and connection information.
|
|
|
|
func (db *DB) Open() error {
|
2022-02-03 15:32:03 +08:00
|
|
|
// Ensure a DSN is set before attempting to open the database.
|
2022-07-22 23:21:12 +08:00
|
|
|
if db.profile.DSN == "" {
|
2022-02-03 15:32:03 +08:00
|
|
|
return fmt.Errorf("dsn required")
|
|
|
|
}
|
|
|
|
|
2023-07-20 20:51:25 +08:00
|
|
|
// Connect to the database with some sane settings:
|
|
|
|
// - No shared-cache: it's obsolete; WAL journal mode is a better solution.
|
|
|
|
// - No foreign key constraints: it's currently disabled by default, but it's a
|
|
|
|
// good practice to be explicit and prevent future surprises on SQLite upgrades.
|
|
|
|
// - Journal mode set to WAL: it's the recommended journal mode for most applications
|
|
|
|
// as it prevents locking issues.
|
|
|
|
//
|
|
|
|
// Notes:
|
|
|
|
// - When using the `modernc.org/sqlite` driver, each pragma must be prefixed with `_pragma=`.
|
|
|
|
//
|
|
|
|
// References:
|
|
|
|
// - https://pkg.go.dev/modernc.org/sqlite#Driver.Open
|
|
|
|
// - https://www.sqlite.org/sharedcache.html
|
|
|
|
// - https://www.sqlite.org/pragma.html
|
|
|
|
sqliteDB, err := sql.Open("sqlite", db.profile.DSN+"?_pragma=foreign_keys(0)&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)")
|
2022-05-01 11:06:29 +08:00
|
|
|
if err != nil {
|
2022-07-22 23:21:12 +08:00
|
|
|
return fmt.Errorf("failed to open db with dsn: %s, err: %w", db.profile.DSN, err)
|
2022-02-03 15:32:03 +08:00
|
|
|
}
|
2023-01-03 23:05:42 +08:00
|
|
|
db.DBInstance = sqliteDB
|
2023-08-26 07:33:45 +08:00
|
|
|
return nil
|
|
|
|
}
|
2022-02-03 15:32:03 +08:00
|
|
|
|
2023-08-26 07:33:45 +08:00
|
|
|
// Migrate applies the latest schema to the database.
|
|
|
|
func (db *DB) Migrate(ctx context.Context) error {
|
2023-02-19 13:36:45 +08:00
|
|
|
if db.profile.Mode == "prod" {
|
2023-06-20 12:18:04 +08:00
|
|
|
_, err := os.Stat(db.profile.DSN)
|
2022-11-27 08:52:43 +08:00
|
|
|
if err != nil {
|
2023-06-20 12:18:04 +08:00
|
|
|
// If db file not exists, we should create a new one with latest schema.
|
|
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
|
|
if err := db.applyLatestSchema(ctx); err != nil {
|
|
|
|
return fmt.Errorf("failed to apply latest schema, err: %w", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("failed to get db file stat, err: %w", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// If db file exists, we should check if we need to migrate the database.
|
|
|
|
currentVersion := version.GetCurrentVersion(db.profile.Mode)
|
|
|
|
migrationHistoryList, err := db.FindMigrationHistoryList(ctx, &MigrationHistoryFind{})
|
2023-01-14 08:00:07 +08:00
|
|
|
if err != nil {
|
2023-06-20 12:18:04 +08:00
|
|
|
return fmt.Errorf("failed to find migration history, err: %w", err)
|
|
|
|
}
|
|
|
|
if len(migrationHistoryList) == 0 {
|
|
|
|
_, err := db.UpsertMigrationHistory(ctx, &MigrationHistoryUpsert{
|
|
|
|
Version: currentVersion,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to upsert migration history, err: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
2022-11-27 08:52:43 +08:00
|
|
|
}
|
2023-01-14 08:00:07 +08:00
|
|
|
|
2023-06-20 12:18:04 +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
|
|
|
|
2023-06-20 12:18:04 +08:00
|
|
|
if version.IsVersionGreaterThan(version.GetSchemaVersion(currentVersion), latestMigrationHistoryVersion) {
|
|
|
|
minorVersionList := getMinorVersionList()
|
2022-07-22 23:21:12 +08:00
|
|
|
|
2023-06-20 12:18:04 +08:00
|
|
|
// backup the raw database file before migration
|
|
|
|
rawBytes, err := os.ReadFile(db.profile.DSN)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to read raw database file, err: %w", err)
|
|
|
|
}
|
|
|
|
backupDBFilePath := fmt.Sprintf("%s/memos_%s_%d_backup.db", db.profile.Data, db.profile.Version, time.Now().Unix())
|
|
|
|
if err := os.WriteFile(backupDBFilePath, rawBytes, 0644); err != nil {
|
|
|
|
return fmt.Errorf("failed to write raw database file, err: %w", err)
|
|
|
|
}
|
|
|
|
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 := db.applyMigrationForMinorVersion(ctx, minorVersion); err != nil {
|
|
|
|
return fmt.Errorf("failed to apply minor version migration: %w", err)
|
|
|
|
}
|
2022-07-02 10:47:16 +08:00
|
|
|
}
|
|
|
|
}
|
2023-06-20 12:18:04 +08:00
|
|
|
println("end migrate")
|
2022-07-22 23:21:12 +08:00
|
|
|
|
2023-06-20 12:18:04 +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
|
|
|
}
|
|
|
|
}
|
2023-02-19 13:36:45 +08:00
|
|
|
} else {
|
2023-02-19 16:34:15 +08:00
|
|
|
// In non-prod mode, we should always migrate the database.
|
2023-02-19 13:36:45 +08:00
|
|
|
if _, err := os.Stat(db.profile.DSN); errors.Is(err, os.ErrNotExist) {
|
|
|
|
if err := db.applyLatestSchema(ctx); err != nil {
|
|
|
|
return fmt.Errorf("failed to apply latest schema: %w", err)
|
|
|
|
}
|
|
|
|
// In demo mode, we should seed the database.
|
|
|
|
if db.profile.Mode == "demo" {
|
|
|
|
if err := db.seed(ctx); err != nil {
|
|
|
|
return fmt.Errorf("failed to seed: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-02-03 15:32:03 +08:00
|
|
|
}
|
|
|
|
|
2022-10-26 23:00:09 +08:00
|
|
|
return nil
|
2022-07-02 10:47:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
latestSchemaFileName = "LATEST__SCHEMA.sql"
|
|
|
|
)
|
|
|
|
|
2022-08-07 10:17:56 +08:00
|
|
|
func (db *DB) applyLatestSchema(ctx context.Context) error {
|
2023-02-19 16:34:15 +08:00
|
|
|
schemaMode := "dev"
|
|
|
|
if db.profile.Mode == "prod" {
|
|
|
|
schemaMode = "prod"
|
|
|
|
}
|
|
|
|
latestSchemaPath := fmt.Sprintf("%s/%s/%s", "migration", schemaMode, latestSchemaFileName)
|
2022-07-02 10:47:16 +08:00
|
|
|
buf, err := migrationFS.ReadFile(latestSchemaPath)
|
2022-05-22 00:59:22 +08:00
|
|
|
if err != nil {
|
2022-07-02 10:47:16 +08:00
|
|
|
return fmt.Errorf("failed to read latest schema %q, error %w", latestSchemaPath, err)
|
2022-05-22 00:59:22 +08:00
|
|
|
}
|
2022-07-02 10:47:16 +08:00
|
|
|
stmt := string(buf)
|
2022-08-07 10:17:56 +08:00
|
|
|
if err := db.execute(ctx, stmt); err != nil {
|
2022-07-02 10:47:16 +08:00
|
|
|
return fmt.Errorf("migrate error: statement:%s err=%w", stmt, err)
|
|
|
|
}
|
|
|
|
return nil
|
2022-07-01 20:39:48 +08:00
|
|
|
}
|
|
|
|
|
2022-08-07 10:17:56 +08:00
|
|
|
func (db *DB) 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 {
|
2022-11-27 08:52:43 +08:00
|
|
|
return fmt.Errorf("failed to read ddl files, err: %w", err)
|
2022-03-28 23:38:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
sort.Strings(filenames)
|
2022-07-02 10:47:16 +08:00
|
|
|
migrationStmt := ""
|
2022-03-28 23:38:12 +08:00
|
|
|
|
|
|
|
// Loop over all migration files and execute them in order.
|
|
|
|
for _, filename := range filenames {
|
2022-07-02 10:47:16 +08:00
|
|
|
buf, err := migrationFS.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to read minor version migration file, filename=%s err=%w", filename, err)
|
|
|
|
}
|
|
|
|
stmt := string(buf)
|
|
|
|
migrationStmt += stmt
|
2022-08-07 10:17:56 +08:00
|
|
|
if err := db.execute(ctx, stmt); err != nil {
|
2022-07-02 10:47:16 +08:00
|
|
|
return fmt.Errorf("migrate error: statement:%s err=%w", stmt, err)
|
2022-03-28 23:38:12 +08:00
|
|
|
}
|
|
|
|
}
|
2022-07-02 10:47:16 +08:00
|
|
|
|
2023-07-20 23:15:56 +08:00
|
|
|
// Upsert the newest version to migration_history.
|
2022-11-27 08:52:43 +08:00
|
|
|
version := minorVersion + ".0"
|
2023-07-20 23:15:56 +08:00
|
|
|
if _, err = db.UpsertMigrationHistory(ctx, &MigrationHistoryUpsert{
|
2022-11-27 08:52:43 +08:00
|
|
|
Version: version,
|
2022-07-02 10:47:16 +08:00
|
|
|
}); err != nil {
|
2022-11-27 08:52:43 +08:00
|
|
|
return fmt.Errorf("failed to upsert migration history with version: %s, err: %w", version, err)
|
2022-07-02 10:47:16 +08:00
|
|
|
}
|
|
|
|
|
2023-07-20 23:15:56 +08:00
|
|
|
return nil
|
2022-03-28 23:38:12 +08:00
|
|
|
}
|
|
|
|
|
2022-08-07 10:17:56 +08:00
|
|
|
func (db *DB) 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 {
|
2022-11-27 08:52:43 +08:00
|
|
|
return fmt.Errorf("failed to read seed files, err: %w", err)
|
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 {
|
2022-07-02 10:47:16 +08:00
|
|
|
buf, err := seedFS.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to read seed file, filename=%s err=%w", filename, err)
|
|
|
|
}
|
|
|
|
stmt := string(buf)
|
2022-08-07 10:17:56 +08:00
|
|
|
if err := db.execute(ctx, stmt); err != nil {
|
2022-07-02 10:47:16 +08:00
|
|
|
return fmt.Errorf("seed error: statement:%s err=%w", stmt, err)
|
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.
|
2022-08-07 10:17:56 +08:00
|
|
|
func (db *DB) execute(ctx context.Context, stmt string) error {
|
2023-01-03 23:05:42 +08:00
|
|
|
tx, err := db.DBInstance.Begin()
|
2022-02-03 15:32:03 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
|
|
|
|
2022-08-07 10:17:56 +08:00
|
|
|
if _, err := tx.ExecContext(ctx, stmt); err != nil {
|
2022-11-27 08:52:43 +08:00
|
|
|
return fmt.Errorf("failed to execute statement, err: %w", err)
|
2022-08-07 10:17:56 +08:00
|
|
|
}
|
|
|
|
|
2022-08-24 21:53:12 +08:00
|
|
|
return tx.Commit()
|
2022-02-03 15:32:03 +08:00
|
|
|
}
|
|
|
|
|
2022-07-02 10:47:16 +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]+$`)
|
2022-07-02 10:47:16 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2022-07-02 10:47:16 +08:00
|
|
|
if file.IsDir() && minorDirRegexp.MatchString(path) {
|
|
|
|
minorVersionList = append(minorVersionList, file.Name())
|
|
|
|
}
|
2022-02-03 15:32:03 +08:00
|
|
|
|
2022-07-02 10:47:16 +08:00
|
|
|
return nil
|
|
|
|
}); err != nil {
|
|
|
|
panic(err)
|
2022-07-02 01:06:28 +08:00
|
|
|
}
|
2022-07-02 10:47:16 +08:00
|
|
|
|
2023-01-07 13:58:42 +08:00
|
|
|
sort.Sort(version.SortVersion(minorVersionList))
|
2022-07-02 10:47:16 +08:00
|
|
|
|
|
|
|
return minorVersionList
|
|
|
|
}
|