Files
2026-11-29 19:35:13 +01:00

281 lines
11 KiB
Go

package repository
import (
"context"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/database/dbengine"
"github.com/phishingclub/phishingclub/testdb"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// TestArrayINStatements checks the IN lists a postgres statement binds as
// one array, and the ones it leaves as gorm builds them
func TestArrayINStatements(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newProgramTestDB(t)
dry := db.Session(&gorm.Session{DryRun: true})
a, b := uuid.New(), uuid.New()
id := clause.Column{Name: "id"}
build := func(where ...clause.Expression) (string, int) {
t.Helper()
q := dry.Model(&database.CampaignRecipient{})
for _, w := range where {
q = q.Where(w)
}
stmt := q.Find(&[]database.CampaignRecipient{}).Statement
return stmt.SQL.String(), len(stmt.Vars)
}
sub := db.Model(&database.Campaign{}).Select("id")
cases := []struct {
name string
where clause.Expression
sql string
vars int
}{
{"list", clause.IN{Column: id, Values: []any{a, b}}, `"id" = ANY($1)`, 1},
{"not", clause.Not(clause.IN{Column: id, Values: []any{a, &b}}), `"id" <> ALL($1)`, 1},
{"or", clause.Or(clause.IN{Column: id, Values: []any{a, b}}, clause.Eq{Column: "x", Value: 1}), `("id" = ANY($1) OR "x" = $2)`, 2},
{"one value", clause.IN{Column: id, Values: []any{a}}, `"id" = $1`, 1},
{"empty", clause.IN{Column: id, Values: []any{}}, `"id" IN (NULL)`, 0},
{"sub query", clause.IN{Column: id, Values: []any{a, sub}}, `"id" IN ($1,SELECT`, 1},
{"expression column", clause.IN{Column: clause.Expr{SQL: "LOWER(x)"}, Values: []any{"a", "b"}}, `IN ($1,$2)`, 2},
}
for _, c := range cases {
sql, vars := build(c.where)
if !strings.Contains(sql, c.sql) || vars != c.vars {
t.Errorf("%s: got %s with %d vars, want %s with %d", c.name, sql, vars, c.sql, c.vars)
}
}
// the statement keeps its clause, a second build gives the same text
q := dry.Model(&database.CampaignRecipient{}).Where(clause.IN{Column: id, Values: []any{a, b}})
first := q.Find(&[]database.CampaignRecipient{}).Statement.SQL.String()
second := q.Find(&[]database.CampaignRecipient{}).Statement.SQL.String()
if first != second {
t.Fatalf("the rewrite changed the statement: %s then %s", first, second)
}
}
// TestArrayINValues checks an array IN finds the same rows as an IN list,
// NULL and nil pointers included, on each engine, and on postgres in every
// supported pgx query exec mode (config.CheckQueryExecMode)
func TestArrayINValues(t *testing.T) {
modes := []string{""}
if testdb.IsPostgres() {
modes = append(modes, "cache_describe", "describe_exec")
}
for _, mode := range modes {
name := mode
if name == "" {
name = "default"
}
t.Run(name, func(t *testing.T) {
arrayINValues(t, newProgramTestDBExecMode(t, mode))
})
}
}
func arrayINValues(t *testing.T, db *gorm.DB) {
camp := ptrUUID()
ids := addSends(t, db, camp, 5)
var nilID *uuid.UUID
count := func(where clause.Expression) int64 {
t.Helper()
var n int64
if err := db.Model(&database.CampaignRecipient{}).Where(where).Count(&n).Error; err != nil {
t.Fatalf("count: %v", err)
}
return n
}
in := clause.IN{Column: clause.Column{Name: "id"}, Values: []any{*ids[0], ids[1], ids[2].String(), nilID, nil}}
if got := count(in); got != 3 {
t.Fatalf("in: %d rows, want 3", got)
}
// NOT IN with a NULL in the list matches no row on both engines
if got := count(clause.Not(in)); got != 0 {
t.Fatalf("not in with a null: %d rows, want 0", got)
}
notIn := clause.Not(clause.IN{Column: clause.Column{Name: "id"}, Values: []any{*ids[0], *ids[1]}})
if got := count(notIn); got != 3 {
t.Fatalf("not in: %d rows, want 3", got)
}
}
// TestVeryLargeINLists checks a group and a campaign of 70000 people on
// postgres: more ids than postgres binds in one statement (65535) go into
// one array parameter, through the group preload, a group member removal and
// the schedule that keeps only the given people. sqlite stops near 32766
// bound values, its accepted limit.
func TestVeryLargeINLists(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newProgramTestDB(t)
if err := db.AutoMigrate(&database.RecipientGroup{}, &database.RecipientGroupRecipient{}, &database.Company{}); err != nil {
t.Fatalf("migrate: %v", err)
}
ctx := context.Background()
const people = 70000
now := time.Now().UTC().Truncate(time.Microsecond)
groupID, camp := uuid.New(), uuid.New()
if err := db.Create(&database.RecipientGroup{ID: &groupID, CreatedAt: &now, UpdatedAt: &now, Name: "big"}).Error; err != nil {
t.Fatalf("group: %v", err)
}
recipients := make([]*database.Recipient, 0, people)
links := make([]*database.RecipientGroupRecipient, 0, people)
sends := make([]*database.CampaignRecipient, 0, people)
ids := make([]*uuid.UUID, people)
for i := range ids {
rid, sid := uuid.New(), uuid.New()
ids[i] = &rid
email := rid.String() + "@example.com"
recipients = append(recipients, &database.Recipient{ID: &rid, CreatedAt: &now, UpdatedAt: &now, Email: &email})
links = append(links, &database.RecipientGroupRecipient{RecipientID: &rid, RecipientGroupID: &groupID})
sends = append(sends, &database.CampaignRecipient{ID: &sid, CreatedAt: &now, UpdatedAt: &now, CampaignID: &camp, RecipientID: &rid})
}
for _, batch := range []any{recipients, links, sends} {
if err := db.CreateInBatches(batch, 2000).Error; err != nil {
t.Fatalf("seed: %v", err)
}
}
groups := &RecipientGroup{DB: db}
start := time.Now()
group, err := groups.GetByID(ctx, &groupID, &RecipientGroupOption{WithRecipients: true})
if err != nil {
t.Fatalf("group with members: %v", err)
}
if len(group.Recipients) != people {
t.Fatalf("%d members loaded, want %d", len(group.Recipients), people)
}
t.Logf("group of %d members loaded in %s", people, time.Since(start))
// the schedule keeps every person but the last ten
if err := (&CampaignRecipient{DB: db}).DeleteRecipientsNotIn(ctx, &camp, ids[:people-10]); err != nil {
t.Fatalf("delete not in: %v", err)
}
if got := countWhere(t, db, &database.CampaignRecipient{}, "campaign_id", camp); got != people-10 {
t.Fatalf("%d sends left, want %d", got, people-10)
}
// an empty list deletes nothing, as NOT IN (NULL) on sqlite
if err := (&CampaignRecipient{DB: db}).DeleteRecipientsNotIn(ctx, &camp, nil); err != nil {
t.Fatalf("delete not in nothing: %v", err)
}
if got := countWhere(t, db, &database.CampaignRecipient{}, "campaign_id", camp); got != people-10 {
t.Fatalf("an empty list deleted sends, %d left", got)
}
if err := groups.RemoveRecipients(ctx, &groupID, ids[:people-1]); err != nil {
t.Fatalf("remove members: %v", err)
}
if got := countWhere(t, db, &database.RecipientGroupRecipient{}, "recipient_group_id", groupID); got != 1 {
t.Fatalf("%d members left, want 1", got)
}
}
// TestNotInEmptyAndNilLists checks DeleteRecipientsNotIn and
// RemoveRecipients with an empty list and with nil ids give the same rows on
// both engines: an empty keep list or one with a nil id deletes nothing (NOT
// IN with a NULL matches no row, and <> ALL of an empty array must not match
// every row), an empty remove list removes nothing, a nil id in a remove
// list is ignored
func TestNotInEmptyAndNilLists(t *testing.T) {
db := newProgramTestDB(t)
if err := db.AutoMigrate(&database.RecipientGroup{}, &database.RecipientGroupRecipient{}); err != nil {
t.Fatalf("migrate: %v", err)
}
ctx := context.Background()
sends := &CampaignRecipient{DB: db}
camp := ptrUUID()
addSends(t, db, camp, 3)
// an anonymized row has no recipient, NOT IN never matches it
if err := db.Create(&database.CampaignRecipient{ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(), CampaignID: camp}).Error; err != nil {
t.Fatalf("anonymized row: %v", err)
}
var recipients []*uuid.UUID
if err := db.Model(&database.CampaignRecipient{}).Where("campaign_id = ? AND recipient_id IS NOT NULL", camp).
Pluck("recipient_id", &recipients).Error; err != nil || len(recipients) != 3 {
t.Fatalf("recipients: %v", err)
}
left := func() int64 {
t.Helper()
return countWhere(t, db, &database.CampaignRecipient{}, "campaign_id", *camp)
}
for name, keep := range map[string][]*uuid.UUID{
"nil": nil,
"empty": {},
"only nil": {nil},
"nil member": {recipients[0], nil},
} {
if err := sends.DeleteRecipientsNotIn(ctx, camp, keep); err != nil {
t.Fatalf("%s: delete not in: %v", name, err)
}
if got := left(); got != 4 {
t.Fatalf("%s: %d sends left, want 4", name, got)
}
}
if err := sends.DeleteRecipientsNotIn(ctx, camp, recipients[:1]); err != nil {
t.Fatalf("delete not in: %v", err)
}
if got := left(); got != 2 {
t.Fatalf("%d sends left, want the kept one and the anonymized one", got)
}
groups := &RecipientGroup{DB: db}
groupID := uuid.New()
if err := db.Create(&database.RecipientGroup{ID: &groupID, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: "g"}).Error; err != nil {
t.Fatalf("group: %v", err)
}
members := []*uuid.UUID{ptrUUID(), ptrUUID(), ptrUUID()}
for _, m := range members {
if err := db.Create(&database.RecipientGroupRecipient{RecipientID: m, RecipientGroupID: &groupID}).Error; err != nil {
t.Fatalf("member: %v", err)
}
}
inGroup := func() int64 {
t.Helper()
return countWhere(t, db, &database.RecipientGroupRecipient{}, "recipient_group_id", groupID)
}
for name, remove := range map[string][]*uuid.UUID{"nil": nil, "empty": {}, "only nil": {nil}} {
if err := groups.RemoveRecipients(ctx, &groupID, remove); err != nil {
t.Fatalf("%s: remove: %v", name, err)
}
if got := inGroup(); got != 3 {
t.Fatalf("%s: %d members left, want 3", name, got)
}
}
if err := groups.RemoveRecipients(ctx, &groupID, []*uuid.UUID{members[0], nil}); err != nil {
t.Fatalf("remove with nil: %v", err)
}
if got := inGroup(); got != 2 {
t.Fatalf("%d members left, want 2", got)
}
if err := groups.RemoveRecipients(ctx, &groupID, members[1:2]); err != nil {
t.Fatalf("remove one: %v", err)
}
if got := inGroup(); got != 1 {
t.Fatalf("%d members left, want 1", got)
}
}
// TestNotAllEmptyMatchesNothing checks the postgres helper never turns an
// empty list into a condition that matches every row
func TestNotAllEmptyMatchesNothing(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newProgramTestDB(t)
addSends(t, db, ptrUUID(), 3)
id := clause.Column{Name: "id"}
for name, where := range map[string]clause.Expression{
"not all": dbengine.NotAll(id, nil),
"any of": dbengine.AnyOf(id, nil),
} {
var n int64
if err := db.Model(&database.CampaignRecipient{}).Where(where).Count(&n).Error; err != nil {
t.Fatalf("%s: count: %v", name, err)
}
if n != 0 {
t.Fatalf("%s of an empty list matched %d rows", name, n)
}
}
}