Files
2026-12-01 21:25:01 +01:00

144 lines
4.9 KiB
Go

package repository
import (
"errors"
"fmt"
"path/filepath"
"testing"
"github.com/jackc/pgx/v5/pgconn"
"github.com/mattn/go-sqlite3"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/errs"
"github.com/phishingclub/phishingclub/testdb"
"gorm.io/gorm"
)
// uniqueRow has two unique columns under their own index names
type uniqueRow struct {
ID int `gorm:"primaryKey;autoIncrement:false"`
Name string `gorm:"uniqueIndex:idx_unique_rows_name"`
Other string `gorm:"uniqueIndex:idx_unique_rows_other"`
}
func (uniqueRow) TableName() string { return "unique_rows" }
// TestIsUniqueViolation checks a real unique violation is told apart by its
// constraint on each engine, through the gorm error and errs.Wrap
func TestIsUniqueViolation(t *testing.T) {
db, err := testdb.Open(t, filepath.Join(t.TempDir(), "unique.db"))
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&uniqueRow{}); err != nil {
t.Fatal(err)
}
if err := db.Create(&uniqueRow{ID: 1, Name: "a", Other: "x"}).Error; err != nil {
t.Fatal(err)
}
nameKey := UniqueKey{SQLite: "unique_rows.name", Postgres: "idx_unique_rows_name"}
otherKey := UniqueKey{SQLite: "unique_rows.other", Postgres: "idx_unique_rows_other"}
nameErr := db.Create(&uniqueRow{ID: 2, Name: "a", Other: "y"}).Error
for _, err := range []error{nameErr, errs.Wrap(nameErr), fmt.Errorf("insert: %w", nameErr)} {
if !IsUniqueViolation(err, nameKey) {
t.Fatalf("name violation not found in %v", err)
}
if !IsUniqueViolation(err, AnyUniqueKey) {
t.Fatalf("any key must match %v", err)
}
if IsUniqueViolation(err, otherKey) {
t.Fatalf("the other index must not match %v", err)
}
if IsRetryable(err) {
t.Fatalf("a unique violation is not retryable: %v", err)
}
}
if testdb.IsPostgres() {
// the translated error keeps both the gorm kind and the driver error
if !errors.Is(nameErr, gorm.ErrDuplicatedKey) {
t.Fatalf("want gorm.ErrDuplicatedKey, got %v", nameErr)
}
var pgErr *pgconn.PgError
if !errors.As(nameErr, &pgErr) || pgErr.ConstraintName != "idx_unique_rows_name" {
t.Fatalf("driver error lost: %v", nameErr)
}
}
// the primary key
pkErr := db.Create(&uniqueRow{ID: 1, Name: "b", Other: "z"}).Error
if !IsUniqueViolation(pkErr, AnyUniqueKey) {
t.Fatalf("primary key violation not found in %v", pkErr)
}
if IsUniqueViolation(pkErr, nameKey) {
t.Fatalf("the name index must not match a primary key violation %v", pkErr)
}
// other errors
if IsUniqueViolation(nil, AnyUniqueKey) || IsUniqueViolation(errors.New("boom"), AnyUniqueKey) {
t.Fatal("a plain error is no unique violation")
}
if !IsUniqueViolation(gorm.ErrDuplicatedKey, AnyUniqueKey) || IsUniqueViolation(gorm.ErrDuplicatedKey, nameKey) {
t.Fatal("a bare gorm duplicate matches only any key")
}
if !IsUniqueViolation(errors.New("UNIQUE constraint failed: unique_rows.name"), nameKey) {
t.Fatal("the sqlite message without the driver type must match as before")
}
}
// TestIsRetryable checks the busy and lock errors of each engine
func TestIsRetryable(t *testing.T) {
retry := []error{
sqlite3.Error{Code: sqlite3.ErrBusy},
sqlite3.Error{Code: sqlite3.ErrLocked},
errs.Wrap(sqlite3.Error{Code: sqlite3.ErrBusy}),
&pgconn.PgError{Code: "40001"},
&pgconn.PgError{Code: "40P01"},
&pgconn.PgError{Code: "55P03"},
fmt.Errorf("write: %w", &pgconn.PgError{Code: "40001"}),
}
for _, err := range retry {
if !IsRetryable(err) {
t.Fatalf("want retryable: %v", err)
}
}
noRetry := []error{
nil,
errors.New("database is locked"),
sqlite3.Error{Code: sqlite3.ErrConstraint},
&pgconn.PgError{Code: "23505"},
&pgconn.PgError{Code: "25P02"},
}
for _, err := range noRetry {
if IsRetryable(err) {
t.Fatalf("want not retryable: %v", err)
}
}
}
// TestLureCodeInsertRace inserts the same lure code from two connections at
// once: the second waits for the first and fails on the lure code index, the
// error the schedule redraws a code on
func TestLureCodeInsertRace(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newWriteLockDB(t)
campaignID := ptrUUID()
if err := db.Create(&database.Campaign{ID: campaignID, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Name: "c"}).Error; err != nil {
t.Fatalf("campaign: %v", err)
}
code := "abc123"
send := func() *database.CampaignRecipient {
c := code
return &database.CampaignRecipient{ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(), CampaignID: campaignID, LureCode: &c}
}
err := whileHeld(t, db, func(tx *gorm.DB) error {
return tx.Create(send()).Error
}, func() error {
return db.Create(send()).Error
})
if !IsUniqueViolation(err, UniqueKey{SQLite: "campaign_recipients.lure_code", Postgres: "idx_campaign_recipients_lure_code"}) {
t.Fatalf("second insert: %v, want a lure code unique violation", err)
}
if n := countWhere(t, db, &database.CampaignRecipient{}, "lure_code", code); n != 1 {
t.Fatalf("rows with the code: %d", n)
}
}