memos/test/store/store.go

77 lines
2.2 KiB
Go
Raw Normal View History

2023-04-03 09:53:36 +08:00
package teststore
2023-04-01 22:47:19 +08:00
import (
"context"
"fmt"
"testing"
2023-09-29 09:15:54 +08:00
// sqlite driver.
_ "modernc.org/sqlite"
2024-01-05 21:27:16 +08:00
"github.com/usememos/memos/server/profile"
2023-04-01 22:47:19 +08:00
"github.com/usememos/memos/store"
2023-10-05 23:11:29 +08:00
"github.com/usememos/memos/store/db"
2023-04-01 22:47:19 +08:00
"github.com/usememos/memos/test"
)
func NewTestingStore(ctx context.Context, t *testing.T) *store.Store {
profile := test.GetTestingProfile(t)
2023-10-05 23:11:29 +08:00
dbDriver, err := db.NewDBDriver(profile)
if err != nil {
fmt.Printf("failed to create db driver, error: %+v\n", err)
2023-04-01 22:47:19 +08:00
}
2024-01-05 21:27:16 +08:00
resetTestingDB(ctx, profile, dbDriver)
2023-10-05 23:11:29 +08:00
if err := dbDriver.Migrate(ctx); err != nil {
2023-08-26 07:33:45 +08:00
fmt.Printf("failed to migrate db, error: %+v\n", err)
}
2023-04-01 22:47:19 +08:00
2023-10-05 23:11:29 +08:00
store := store.New(dbDriver, profile)
2023-04-01 22:47:19 +08:00
return store
}
2024-01-05 21:27:16 +08:00
func resetTestingDB(ctx context.Context, profile *profile.Profile, dbDriver store.Driver) {
2024-01-06 16:55:13 +08:00
if profile.Driver == "mysql" {
_, err := dbDriver.GetDB().ExecContext(ctx, `
DROP TABLE IF EXISTS migration_history;
DROP TABLE IF EXISTS system_setting;
DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS user_setting;
DROP TABLE IF EXISTS memo;
DROP TABLE IF EXISTS memo_organizer;
DROP TABLE IF EXISTS memo_relation;
DROP TABLE IF EXISTS resource;
DROP TABLE IF EXISTS tag;
DROP TABLE IF EXISTS activity;
DROP TABLE IF EXISTS storage;
DROP TABLE IF EXISTS idp;
DROP TABLE IF EXISTS inbox;
2024-02-09 21:59:45 +08:00
DROP TABLE IF EXISTS webhook;
DROP TABLE IF EXISTS reaction;`)
2024-01-06 16:55:13 +08:00
if err != nil {
fmt.Printf("failed to reset testing db, error: %+v\n", err)
panic(err)
}
} else if profile.Driver == "postgres" {
_, err := dbDriver.GetDB().ExecContext(ctx, `
DROP TABLE IF EXISTS migration_history CASCADE;
DROP TABLE IF EXISTS system_setting CASCADE;
DROP TABLE IF EXISTS "user" CASCADE;
DROP TABLE IF EXISTS user_setting CASCADE;
DROP TABLE IF EXISTS memo CASCADE;
DROP TABLE IF EXISTS memo_organizer CASCADE;
DROP TABLE IF EXISTS memo_relation CASCADE;
DROP TABLE IF EXISTS resource CASCADE;
DROP TABLE IF EXISTS tag CASCADE;
DROP TABLE IF EXISTS activity CASCADE;
DROP TABLE IF EXISTS storage CASCADE;
DROP TABLE IF EXISTS idp CASCADE;
DROP TABLE IF EXISTS inbox CASCADE;
2024-02-09 21:59:45 +08:00
DROP TABLE IF EXISTS webhook CASCADE;
DROP TABLE IF EXISTS reaction CASCADE;`)
2024-01-05 21:27:16 +08:00
if err != nil {
fmt.Printf("failed to reset testing db, error: %+v\n", err)
panic(err)
}
}
}