added 'default' types (int, string, varchar(min,max)) and it works ! \o/

This commit is contained in:
Adrien Marquès 2018-05-22 20:27:51 +02:00
parent 3c9e154162
commit 5ae2554fba
4 changed files with 104 additions and 8 deletions

12
checker/default/int.go Normal file
View File

@ -0,0 +1,12 @@
package main
func Match(name string) bool {
return name == "int"
}
func Check(value interface{}) bool {
_, intOK := value.(int)
_, uintOK := value.(uint)
return intOK || uintOK
}

11
checker/default/string.go Normal file
View File

@ -0,0 +1,11 @@
package main
func Match(name string) bool {
return name == "string"
}
func Check(value interface{}) bool {
_, OK := value.(string)
return OK
}

View File

@ -0,0 +1,73 @@
package main
import (
"regexp"
"strconv"
)
var min *uint64 = nil
var max *uint64 = nil
func Match(name string) bool {
/* (1) Create regexp */
re, err := regexp.Compile(`^varchar\((\d+), ?(\d+)\)$`)
if err != nil {
panic(err)
}
/* (2) Check if matches */
matches := re.FindStringSubmatch(name)
if matches == nil || len(matches) < 3 {
return false
}
/* (3) Extract min */
minVal, err := strconv.ParseUint(matches[1], 10, 64)
if err != nil {
return false
}
min = &minVal
/* (4) Extract max */
maxVal, err := strconv.ParseUint(matches[2], 10, 64)
if err != nil {
return false
}
/* (5) Check that min <= max */
if maxVal < minVal {
panic("varchar(x, y) ; constraint violation : x <= y")
}
max = &maxVal
return true
}
func Check(value interface{}) bool {
/* (1) Check if string */
strval, ok := value.(string)
if !ok {
return false
}
/* (2) Check if sizes set */
if min == nil || max == nil {
return false
}
/* (3) Check min */
if uint64(len(strval)) < *min {
return false
}
/* (4) Check max */
if uint64(len(strval)) > *max {
return false
}
return true
}

View File

@ -8,7 +8,7 @@ import (
// CreateRegistry creates an empty type registry
// if TRUE is given, it will use default Types
// see ./default_types.go
// see ./default/ folder
func CreateRegistry(useDefaultTypes bool) *TypeRegistry {
return &TypeRegistry{
Types: make([]Type, 0),
@ -67,7 +67,7 @@ func (tr *TypeRegistry) Add(pluginName string) error {
}
// Checks the 'value' which must be of type 'name'
func (tr TypeRegistry) Run(name string, value interface{}) bool {
func (tr TypeRegistry) Run(name string, value interface{}) error {
var T *Type = nil
@ -79,18 +79,18 @@ func (tr TypeRegistry) Run(name string, value interface{}) bool {
T = &t
break
}
// else log
fmt.Printf("does not match\n")
}
/* (2) Abort if no matching type */
if T == nil {
return false
return fmt.Errorf("No matching type")
}
/* (3) Check */
fmt.Printf("Check is %t\n", T.Check(value))
return T.Check(value)
if !T.Check(value) {
return fmt.Errorf("Does not match")
}
return nil
}