github.com/mailru/activerecord@v1.12.2/internal/pkg/parser/trigger.go (about) 1 package parser 2 3 import ( 4 "fmt" 5 "go/ast" 6 "strings" 7 8 "github.com/mailru/activerecord/internal/pkg/arerror" 9 "github.com/mailru/activerecord/internal/pkg/ds" 10 ) 11 12 // Список доступных триггеров 13 var availableTriggers = map[string]map[string]bool{ 14 "RepairTuple": {"Defaults": true}, 15 "DublicateUniqTuple": {}, 16 } 17 18 // Парсинг заявленных триггеров в описании модели 19 func ParseTrigger(dst *ds.RecordPackage, fields []*ast.Field) error { 20 for _, field := range fields { 21 if field.Names == nil || len(field.Names) != 1 { 22 return &arerror.ErrParseTriggerDecl{Err: arerror.ErrNameDeclaration} 23 } 24 25 if err := checkBoolType(field.Type); err != nil { 26 return &arerror.ErrParseTriggerDecl{Err: arerror.ErrTypeNotBool} 27 } 28 29 trigger := ds.TriggerDeclaration{ 30 Name: field.Names[0].Name, 31 Func: field.Names[0].Name, 32 Params: map[string]bool{}, 33 ImportName: "trigger" + field.Names[0].Name, 34 } 35 36 if err := ParseTriggerTag(&trigger, field); err != nil { 37 return fmt.Errorf("error parse trigger tag: %w", err) 38 } 39 40 if trigger.Pkg == "" { 41 return &arerror.ErrParseTriggerDecl{Name: field.Names[0].Name, Err: arerror.ErrParseTriggerPackageNotDefined} 42 } 43 44 imp, err := dst.FindOrAddImport(trigger.Pkg, trigger.ImportName) 45 if err != nil { 46 return &arerror.ErrParseTriggerDecl{Name: trigger.Name, Err: err} 47 } 48 49 trigger.ImportName = imp.ImportName 50 51 if err = dst.AddTrigger(trigger); err != nil { 52 return err 53 } 54 } 55 56 return nil 57 } 58 59 func ParseTriggerTag(trigger *ds.TriggerDeclaration, field *ast.Field) error { 60 atr, ex := availableTriggers[field.Names[0].Name] 61 if !ex { 62 return &arerror.ErrParseTriggerDecl{Name: field.Names[0].Name, Err: arerror.ErrUnknown} 63 } 64 65 tagParam, err := splitTag(field, CheckFlagEmpty, map[TagNameType]ParamValueRule{}) 66 if err != nil { 67 return &arerror.ErrParseTriggerDecl{Name: field.Names[0].Name, Err: err} 68 } 69 70 for _, kv := range tagParam { 71 switch kv[0] { 72 case "pkg": 73 trigger.Pkg = kv[1] 74 case "func": 75 trigger.Func = kv[1] 76 case "param": 77 for _, param := range strings.Split(kv[1], ",") { 78 if _, ex := atr[param]; ex { 79 trigger.Params[param] = true 80 } else { 81 return &arerror.ErrParseTriggerTagDecl{Name: field.Names[0].Name, TagName: kv[0], TagValue: kv[1], Err: arerror.ErrParseTagUnknown} 82 } 83 } 84 default: 85 return &arerror.ErrParseTriggerTagDecl{Name: field.Names[0].Name, TagName: kv[0], TagValue: kv[1], Err: arerror.ErrParseTagUnknown} 86 } 87 } 88 89 return nil 90 }