memos/store/db/db.go

252 lines
6 KiB
Go
Raw Normal View History

2022-05-22 00:59:22 +08:00
package db
2022-02-03 15:32:03 +08:00
import (
"database/sql"
"embed"
"errors"
"fmt"
"io/fs"
2022-05-01 11:06:29 +08:00
"os"
"regexp"
2022-02-03 15:32:03 +08:00
"sort"
2022-06-27 22:09:06 +08:00
"github.com/usememos/memos/common"
"github.com/usememos/memos/server/profile"
2022-02-03 15:32:03 +08:00
_ "github.com/mattn/go-sqlite3"
)
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
2022-02-03 15:32:03 +08:00
Db *sql.DB
2022-02-06 10:37:09 +08:00
// datasource name
2022-02-03 15:32:03 +08:00
DSN string
2022-05-02 09:40:25 +08:00
// mode should be prod or dev
2022-02-06 10:37:09 +08:00
mode string
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-03-29 20:53:43 +08:00
DSN: profile.DSN,
mode: profile.Mode,
2022-02-03 15:32:03 +08:00
}
return db
}
func (db *DB) Open() (err error) {
// Ensure a DSN is set before attempting to open the database.
if db.DSN == "" {
return fmt.Errorf("dsn required")
}
// Connect to the database.
2022-05-01 11:06:29 +08:00
sqlDB, err := sql.Open("sqlite3", db.DSN)
if err != nil {
2022-02-06 10:37:09 +08:00
return fmt.Errorf("failed to open db with dsn: %s, err: %w", db.DSN, err)
2022-02-03 15:32:03 +08:00
}
2022-05-01 11:06:29 +08:00
db.Db = sqlDB
// If mode is dev, we should migrate and seed the database.
if db.mode == "dev" {
if err := db.applyLatestSchema(); err != nil {
return fmt.Errorf("failed to apply latest schema: %w", err)
2022-03-28 23:38:12 +08:00
}
if err := db.seed(); err != nil {
return fmt.Errorf("failed to seed: %w", err)
2022-02-06 10:37:09 +08:00
}
2022-05-01 11:06:29 +08:00
} else {
// If db file not exists, we should migrate the database.
if _, err := os.Stat(db.DSN); errors.Is(err, os.ErrNotExist) {
err := db.applyLatestSchema()
if err != nil {
return fmt.Errorf("failed to apply latest schema: %w", err)
}
} else {
err := db.createMigrationHistoryTable()
if err != nil {
return fmt.Errorf("failed to create migration_history table: %w", err)
}
currentVersion := common.GetCurrentVersion(db.mode)
migrationHistory, err := findMigrationHistory(db.Db, &MigrationHistoryFind{})
if err != nil {
return err
}
if migrationHistory == nil {
migrationHistory, err = upsertMigrationHistory(db.Db, &MigrationHistoryCreate{
Version: currentVersion,
Statement: "",
})
if err != nil {
return err
}
2022-05-01 11:06:29 +08:00
}
if common.IsVersionGreaterThan(currentVersion, migrationHistory.Version) {
minorVersionList := getMinorVersionList()
for _, minorVersion := range minorVersionList {
normalizedVersion := minorVersion + ".0"
if common.IsVersionGreaterThan(normalizedVersion, migrationHistory.Version) && common.IsVersionGreaterOrEqualThan(currentVersion, normalizedVersion) {
err := db.applyMigrationForMinorVersion(minorVersion)
if err != nil {
return fmt.Errorf("failed to apply minor version migration: %w", err)
}
}
}
2022-05-01 11:06:29 +08:00
}
}
2022-02-03 15:32:03 +08:00
}
return err
}
const (
latestSchemaFileName = "LATEST__SCHEMA.sql"
)
func (db *DB) applyLatestSchema() error {
latestSchemaPath := fmt.Sprintf("%s/%s", "migration", latestSchemaFileName)
buf, err := migrationFS.ReadFile(latestSchemaPath)
2022-05-22 00:59:22 +08:00
if err != nil {
return fmt.Errorf("failed to read latest schema %q, error %w", latestSchemaPath, err)
2022-05-22 00:59:22 +08:00
}
stmt := string(buf)
if err := db.execute(stmt); err != nil {
return fmt.Errorf("migrate error: statement:%s err=%w", stmt, err)
}
return nil
}
func (db *DB) applyMigrationForMinorVersion(minorVersion string) error {
filenames, err := fs.Glob(migrationFS, fmt.Sprintf("%s/%s/*.sql", "migration", minorVersion))
2022-03-28 23:38:12 +08:00
if err != nil {
return err
}
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 {
return fmt.Errorf("failed to read minor version migration file, filename=%s err=%w", filename, err)
}
stmt := string(buf)
migrationStmt += stmt
if err := db.execute(stmt); err != nil {
return fmt.Errorf("migrate error: statement:%s err=%w", stmt, err)
2022-03-28 23:38:12 +08:00
}
}
// upsert the newest version to migration_history
if _, err = upsertMigrationHistory(db.Db, &MigrationHistoryCreate{
Version: minorVersion + ".0",
Statement: migrationStmt,
}); err != nil {
return err
}
2022-03-28 23:38:12 +08:00
return nil
}
2022-02-03 15:32:03 +08:00
func (db *DB) seed() error {
filenames, err := fs.Glob(seedFS, fmt.Sprintf("%s/*.sql", "seed"))
if err != nil {
return err
}
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 {
return fmt.Errorf("failed to read seed file, filename=%s err=%w", filename, err)
}
stmt := string(buf)
if err := db.execute(stmt); err != nil {
return fmt.Errorf("seed error: statement:%s err=%w", stmt, err)
2022-02-03 15:32:03 +08:00
}
}
return nil
}
// excecute runs a single SQL statement within a transaction.
func (db *DB) execute(stmt string) error {
2022-02-03 15:32:03 +08:00
tx, err := db.Db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(stmt); err != nil {
2022-02-03 15:32:03 +08:00
return err
}
return tx.Commit()
}
// minorDirRegexp is a regular expression for minor version directory.
var minorDirRegexp = regexp.MustCompile(`^migration/[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.Strings(minorVersionList)
return minorVersionList
}
// createMigrationHistoryTable creates the migration_history table if it doesn't exist.
func (db *DB) createMigrationHistoryTable() error {
table, err := findTable(db.Db, "migration_history")
2022-05-22 09:29:34 +08:00
if err != nil {
2022-02-03 15:32:03 +08:00
return err
}
// TODO(steven): Drop the migration_history table if it exists temporarily.
if table != nil {
err = db.execute(`
DROP TABLE IF EXISTS migration_history;
`)
2022-07-02 01:06:28 +08:00
if err != nil {
return err
}
2022-05-22 09:29:34 +08:00
}
err = createTable(db.Db, `
CREATE TABLE migration_history (
version TEXT NOT NULL PRIMARY KEY,
statement TEXT NOT NULL DEFAULT '',
created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now'))
);
`)
if err != nil {
return err
}
2022-05-22 09:29:34 +08:00
return nil
2022-02-03 15:32:03 +08:00
}