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

119 lines
3.9 KiB
Go

package testdb
import (
"fmt"
"regexp"
"gorm.io/gorm"
)
// Test only. Trigger and function DDL takes no bind parameters, so the
// helpers below put names into the statement. Every value is checked against
// a strict pattern right before it is used.
var (
identifierPattern = regexp.MustCompile(`^[a-z_][a-z0-9_]{0,62}$`)
triggerEventPattern = regexp.MustCompile(`^(BEFORE|AFTER) (INSERT|UPDATE|DELETE)( OF [a-z_][a-z0-9_]{0,62})?$`)
conditionPattern = regexp.MustCompile(`^[A-Za-z0-9_ .=<>']*$`)
messagePattern = regexp.MustCompile(`^[A-Za-z0-9 _]+$`)
)
// checkTriggerParts fails unless every part of a trigger matches its pattern
func checkTriggerParts(name, event, table, when, message string) error {
switch {
case !identifierPattern.MatchString(name):
return fmt.Errorf("testdb: invalid trigger name %q", name)
case !identifierPattern.MatchString(table):
return fmt.Errorf("testdb: invalid table name %q", table)
case event != "" && !triggerEventPattern.MatchString(event):
return fmt.Errorf("testdb: invalid trigger event %q", event)
case !conditionPattern.MatchString(when):
return fmt.Errorf("testdb: invalid trigger condition %q", when)
case message != "" && !messagePattern.MatchString(message):
return fmt.Errorf("testdb: invalid trigger message %q", message)
}
return nil
}
// CreateFailTrigger adds a trigger that makes a write fail with message, to
// test how code handles a failed statement. event is the trigger event such
// as "BEFORE DELETE" or "BEFORE UPDATE OF status", when is an optional
// condition on OLD and NEW. Every argument is a constant of the test.
//
// On postgres the trigger fires even with foreign key checks off, which turn
// off normal triggers too.
func CreateFailTrigger(db *gorm.DB, name, event, table, when, message string) error {
if event == "" || message == "" {
return fmt.Errorf("testdb: trigger event and message are required")
}
if err := checkTriggerParts(name, event, table, when, message); err != nil {
return err
}
if !IsPostgres() {
condition := ""
if when != "" {
condition = " WHEN " + when
}
return db.Exec(fmt.Sprintf(
"CREATE TRIGGER %s %s ON %s%s BEGIN SELECT RAISE(ABORT, '%s'); END",
name, event, table, condition, message,
)).Error
}
if err := db.Exec(fmt.Sprintf(
"CREATE FUNCTION %s_fn() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION '%s'; END $$",
name, message,
)).Error; err != nil {
return err
}
condition := ""
if when != "" {
condition = " WHEN (" + when + ")"
}
if err := db.Exec(fmt.Sprintf(
"CREATE TRIGGER %s %s ON %s FOR EACH ROW%s EXECUTE FUNCTION %s_fn()",
name, event, table, condition, name,
)).Error; err != nil {
return err
}
return db.Exec(fmt.Sprintf("ALTER TABLE %s ENABLE ALWAYS TRIGGER %s", table, name)).Error
}
// DropFailTrigger removes a trigger made by CreateFailTrigger
func DropFailTrigger(db *gorm.DB, name, table string) error {
if err := checkTriggerParts(name, "", table, "", ""); err != nil {
return err
}
if !IsPostgres() {
return db.Exec("DROP TRIGGER " + name).Error
}
if err := db.Exec(fmt.Sprintf("DROP TRIGGER %s ON %s", name, table)).Error; err != nil {
return err
}
return db.Exec(fmt.Sprintf("DROP FUNCTION %s_fn()", name)).Error
}
// IndexNames returns the names of the indexes whose name matches the LIKE
// pattern, sorted
func IndexNames(db *gorm.DB, like string) ([]string, error) {
var names []string
query := "SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE ? ORDER BY name"
if IsPostgres() {
query = "SELECT indexname FROM pg_indexes WHERE schemaname = current_schema() AND indexname LIKE ? ORDER BY indexname"
}
err := db.Raw(query, like).Scan(&names).Error
return names, err
}
// HasIndex reports whether an index of the name exists
func HasIndex(db *gorm.DB, name string) (bool, error) {
names, err := IndexNames(db, name)
if err != nil {
return false, err
}
for _, n := range names {
if n == name {
return true, nil
}
}
return false, nil
}