1
0

client_email_lower_index_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package database
  2. import (
  3. "path/filepath"
  4. "strings"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. )
  8. // The migration runs on every start, so its guard has to actually match the
  9. // index it created — otherwise every boot re-issues the CREATE.
  10. func TestMigrateClientEmailLowerIndexIsIdempotent(t *testing.T) {
  11. if err := InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  12. t.Fatalf("InitDB: %v", err)
  13. }
  14. t.Cleanup(func() { _ = CloseDB() })
  15. if !db.Migrator().HasIndex(&model.ClientRecord{}, "idx_clients_email_lower") {
  16. t.Fatal("idx_clients_email_lower missing after InitDB")
  17. }
  18. if err := migrateClientEmailLowerIndex(); err != nil {
  19. t.Fatalf("second run: %v", err)
  20. }
  21. if !db.Migrator().HasIndex(&model.ClientRecord{}, "idx_clients_email_lower") {
  22. t.Fatal("idx_clients_email_lower vanished after a second run")
  23. }
  24. if IsPostgres() {
  25. return
  26. }
  27. // The identity lookups filter on LOWER(email); without the expression index
  28. // they seq-scan, which is the cost this migration exists to remove.
  29. var plan []struct{ Detail string }
  30. if err := db.Raw("EXPLAIN QUERY PLAN SELECT email FROM clients WHERE LOWER(email) IN ('a')").
  31. Scan(&plan).Error; err != nil {
  32. t.Fatalf("explain: %v", err)
  33. }
  34. used := false
  35. for _, row := range plan {
  36. if strings.Contains(row.Detail, "idx_clients_email_lower") {
  37. used = true
  38. }
  39. }
  40. if !used {
  41. t.Errorf("LOWER(email) lookup does not use idx_clients_email_lower: %+v", plan)
  42. }
  43. }