store.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package teststore
  2. import (
  3. "context"
  4. "log/slog"
  5. "testing"
  6. // sqlite driver.
  7. _ "modernc.org/sqlite"
  8. "github.com/usememos/memos/server/profile"
  9. "github.com/usememos/memos/store"
  10. "github.com/usememos/memos/store/db"
  11. "github.com/usememos/memos/test"
  12. )
  13. func NewTestingStore(ctx context.Context, t *testing.T) *store.Store {
  14. profile := test.GetTestingProfile(t)
  15. dbDriver, err := db.NewDBDriver(profile)
  16. if err != nil {
  17. slog.Error("failed to create db driver", slog.String("error", err.Error()))
  18. }
  19. resetTestingDB(ctx, profile, dbDriver)
  20. store := store.New(dbDriver, profile)
  21. if err := store.Migrate(ctx); err != nil {
  22. slog.Error("failed to migrate db", slog.String("error", err.Error()))
  23. }
  24. return store
  25. }
  26. func resetTestingDB(ctx context.Context, profile *profile.Profile, dbDriver store.Driver) {
  27. if profile.Driver == "mysql" {
  28. _, err := dbDriver.GetDB().ExecContext(ctx, `
  29. DROP TABLE IF EXISTS migration_history;
  30. DROP TABLE IF EXISTS system_setting;
  31. DROP TABLE IF EXISTS user;
  32. DROP TABLE IF EXISTS user_setting;
  33. DROP TABLE IF EXISTS memo;
  34. DROP TABLE IF EXISTS memo_organizer;
  35. DROP TABLE IF EXISTS memo_relation;
  36. DROP TABLE IF EXISTS resource;
  37. DROP TABLE IF EXISTS tag;
  38. DROP TABLE IF EXISTS activity;
  39. DROP TABLE IF EXISTS storage;
  40. DROP TABLE IF EXISTS idp;
  41. DROP TABLE IF EXISTS inbox;
  42. DROP TABLE IF EXISTS webhook;
  43. DROP TABLE IF EXISTS reaction;`)
  44. if err != nil {
  45. slog.Error("failed to reset testing db", slog.String("error", err.Error()))
  46. panic(err)
  47. }
  48. } else if profile.Driver == "postgres" {
  49. _, err := dbDriver.GetDB().ExecContext(ctx, `
  50. DROP TABLE IF EXISTS migration_history CASCADE;
  51. DROP TABLE IF EXISTS system_setting CASCADE;
  52. DROP TABLE IF EXISTS "user" CASCADE;
  53. DROP TABLE IF EXISTS user_setting CASCADE;
  54. DROP TABLE IF EXISTS memo CASCADE;
  55. DROP TABLE IF EXISTS memo_organizer CASCADE;
  56. DROP TABLE IF EXISTS memo_relation CASCADE;
  57. DROP TABLE IF EXISTS resource CASCADE;
  58. DROP TABLE IF EXISTS tag CASCADE;
  59. DROP TABLE IF EXISTS activity CASCADE;
  60. DROP TABLE IF EXISTS storage CASCADE;
  61. DROP TABLE IF EXISTS idp CASCADE;
  62. DROP TABLE IF EXISTS inbox CASCADE;
  63. DROP TABLE IF EXISTS webhook CASCADE;
  64. DROP TABLE IF EXISTS reaction CASCADE;`)
  65. if err != nil {
  66. slog.Error("failed to reset testing db", slog.String("error", err.Error()))
  67. panic(err)
  68. }
  69. }
  70. }