67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
package schema
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
)
|
|
|
|
var (
|
|
requiredAttributes = [2]string{"name", "type"}
|
|
onlySupportedTypes = []string{"string", "int", "float", "bool", "date", "time", "datetime", "uuid", "json", "hash"}
|
|
)
|
|
|
|
func ValidateField(field *Field) error {
|
|
if err := ValidateHashAlgorithm(field); err != nil {
|
|
return err
|
|
}
|
|
if err := ValidateAttributes(field); err != nil {
|
|
return err
|
|
}
|
|
if err := ValidateFieldType(field); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ValidateAttributes(field *Field) error {
|
|
// Check if the field has keys that are necessary for the field
|
|
for _, attribute := range requiredAttributes {
|
|
if _, ok := map[string]any{field.Name: field.Type}[attribute]; !ok {
|
|
return fmt.Errorf("attribute %s is required", attribute)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ValidateFieldType(field *Field) error {
|
|
if !slices.Contains(onlySupportedTypes, field.Type) {
|
|
return fmt.Errorf("unsupported type: %s", field.Type)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ValidateHashAlgorithm(field *Field) error {
|
|
if field.Type != "hash" {
|
|
return nil
|
|
}
|
|
if field.Algorithm == nil {
|
|
return fmt.Errorf("algorithm is required for hash field")
|
|
}
|
|
var hashAlgorithms = []string{"argon2", "bcrypt", "md5", "sha256", "sha512"}
|
|
for _, algorithm := range hashAlgorithms {
|
|
if *field.Algorithm == algorithm {
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("unsupported hash algorithm: %s", *field.Algorithm)
|
|
}
|
|
|
|
func (t *Table) Validate() error {
|
|
for _, field := range t.Schema {
|
|
if err := ValidateField(&field); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|