Skip to content

Commit

Permalink
validator unique columns
Browse files Browse the repository at this point in the history
  • Loading branch information
iesreza committed Oct 29, 2024
1 parent 40b6c3e commit e96a15c
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/validation/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package validation
import (
"context"
"fmt"
"github.com/getevo/evo/v2"
"github.com/getevo/evo/v2/lib/db"
scm "github.com/getevo/evo/v2/lib/db/schema"
"github.com/getevo/evo/v2/lib/generic"
Expand All @@ -19,12 +20,37 @@ import (

var DBValidators = map[*regexp.Regexp]func(match []string, value *generic.Value, stmt *gorm.Statement, field *schema.Field) error{
regexp.MustCompile("^unique$"): uniqueValidator,
regexp.MustCompile("^unique:(.+)$"): uniqueColumnsValidator,
regexp.MustCompile("^fk$"): foreignKeyValidator,
regexp.MustCompile("^enum$"): enumValidator,
regexp.MustCompile(`^before\((\w+)\)$`): beforeValidator,
regexp.MustCompile(`^after\((\w+)\)$`): afterValidator,
}

func uniqueColumnsValidator(match []string, value *generic.Value, stmt *gorm.Statement, field *schema.Field) error {
var columns = strings.Split(match[1], ",")
evo.Dump(columns)

var model = db.Debug().Table(stmt.Table)
for _, item := range stmt.Schema.Fields {
for _, column := range columns {
if item.DBName == column || item.Name == column {
dst, zero := item.ValueOf(context.Background(), reflect.ValueOf(stmt.Model))
if zero {
return nil
}
model = model.Where(column+" =?", dst)
}
}
}
var c int64
model.Count(&c)
if c > 0 {
return fmt.Errorf("duplicate value for %s", strings.Join(columns, ", "))
}
return nil
}

var Validators = map[*regexp.Regexp]func(match []string, value *generic.Value) error{
regexp.MustCompile("^text$"): textValidator,
regexp.MustCompile("^name$"): nameValidator,
Expand Down

0 comments on commit e96a15c

Please sign in to comment.