Documentation
¶
Overview ¶
Package queryfy provides schema validation and querying for dynamic data in Go.
Queryfy is designed to work with map[string]interface{} data structures commonly found in JSON APIs, configuration files, and other dynamic contexts.
Basic usage:
schema := queryfy.Object().
Field("id", queryfy.String().Required()).
Field("amount", queryfy.Number().Min(0))
data := map[string]interface{}{
"id": "order-123",
"amount": 99.99,
}
if err := queryfy.Validate(data, schema); err != nil {
// Handle validation error
}
// Query the data
amount, _ := queryfy.Query(data, "amount")
Index ¶
- func Collect(data interface{}, queryStr string, ...) ([]interface{}, error)
- func ConvertStringToNumber(str string) (float64, bool)
- func ConvertToString(value interface{}) (string, bool)
- func Each(data interface{}, queryStr string, fn func(index int, value interface{}) error) error
- func MustValidate(data interface{}, schema Schema)
- func Query(data interface{}, queryStr string) (interface{}, error)
- func Validate(data interface{}, schema Schema) error
- func ValidateAndTransform(data interface{}, schema Schema, mode ValidationMode) (interface{}, error)
- func ValidateAndTransformAsync(goCtx context.Context, data interface{}, schema Schema, mode ValidationMode) (interface{}, error)
- func ValidateEach(data interface{}, queryStr string, schema Schema, mode ValidationMode) error
- func ValidateValue(value interface{}, expectedType SchemaType, ctx *ValidationContext) bool
- func ValidateWithMode(data interface{}, schema Schema, mode ValidationMode) error
- func WrapError(err error, path string) error
- type AsyncTransformableSchema
- type AsyncValidatorFunc
- type BaseSchema
- func (s *BaseSchema) AllMeta() map[string]interface{}
- func (s *BaseSchema) CheckRequired(value interface{}, ctx *ValidationContext) bool
- func (s *BaseSchema) GetMeta(key string) (interface{}, bool)
- func (s *BaseSchema) IsNullable() bool
- func (s *BaseSchema) IsRequired() bool
- func (s *BaseSchema) SetMeta(key string, value interface{})
- func (s *BaseSchema) SetNullable(nullable bool)
- func (s *BaseSchema) SetRequired(required bool)
- func (s *BaseSchema) Type() SchemaType
- type CompiledSchema
- type FieldError
- type Option
- type Schema
- type SchemaType
- type TransformableSchema
- type TransformationRecord
- type Transformer
- type ValidationContext
- func (c *ValidationContext) AddError(message string, value interface{})
- func (c *ValidationContext) AddFieldError(err FieldError)
- func (c *ValidationContext) CurrentPath() string
- func (c *ValidationContext) Error() error
- func (c *ValidationContext) Errors() []FieldError
- func (c *ValidationContext) HasErrors() bool
- func (c *ValidationContext) HasTransformations() bool
- func (c *ValidationContext) Mode() ValidationMode
- func (c *ValidationContext) PopPath()
- func (c *ValidationContext) PushIndex(index int)
- func (c *ValidationContext) PushPath(segment string)
- func (c *ValidationContext) RecordTransformation(original, result interface{}, transformType string)
- func (c *ValidationContext) Reset()
- func (c *ValidationContext) Transformations() []TransformationRecord
- func (c *ValidationContext) WithIndex(index int, fn func())
- func (c *ValidationContext) WithPath(segment string, fn func())
- type ValidationError
- type ValidationMode
- type Validator
- type ValidatorFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Collect ¶ added in v0.3.0
func Collect(data interface{}, queryStr string, fn func(value interface{}) (interface{}, error)) ([]interface{}, error)
Collect executes a query path and applies a transform function to each matched element, returning the collected results. The path may include wildcards.
func ConvertStringToNumber ¶
ConvertStringToNumber attempts to convert a string to a number. Returns the number and true if successful, 0 and false otherwise.
func ConvertToString ¶
ConvertToString attempts to convert a value to string. Returns the string and true if successful, empty string and false otherwise.
func Each ¶ added in v0.3.0
Each executes a callback for each element matched by a query path. The path may include wildcards (e.g., "items[*]"). If no wildcard is present, the callback is called once with the single matched value.
The callback receives the index and value of each element. Return a non-nil error from the callback to stop iteration early.
func MustValidate ¶
func MustValidate(data interface{}, schema Schema)
MustValidate validates data against a schema and panics on error. This is useful in initialization code where validation errors are fatal.
func Query ¶
Query executes a query against the data and returns the result. Supports dot notation and array indexing:
- "name" - returns the value of field "name"
- "user.email" - returns nested field value
- "items[0]" - returns first element of array
- "items[0].price" - returns field from array element
func Validate ¶
Validate validates data against a schema. Returns a ValidationError containing all validation failures, or nil if valid.
func ValidateAndTransform ¶ added in v0.3.0
func ValidateAndTransform(data interface{}, schema Schema, mode ValidationMode) (interface{}, error)
ValidateAndTransform validates data against a schema and returns the transformed result. If the schema does not support transformation, it falls back to plain validation and returns the original data.
func ValidateAndTransformAsync ¶ added in v0.3.0
func ValidateAndTransformAsync(goCtx context.Context, data interface{}, schema Schema, mode ValidationMode) (interface{}, error)
ValidateAndTransformAsync validates data with async validators and returns the transformed result. If the schema has no async validators, it falls back to synchronous ValidateAndTransform.
func ValidateEach ¶ added in v0.3.0
func ValidateEach(data interface{}, queryStr string, schema Schema, mode ValidationMode) error
ValidateEach executes a query path, then validates each matched element against the given schema. Returns a ValidationError with paths that include the element index (e.g., "[0]: field is required").
The mode parameter controls strict/loose validation.
func ValidateValue ¶
func ValidateValue(value interface{}, expectedType SchemaType, ctx *ValidationContext) bool
ValidateValue is a helper function that validates a single value against its expected type. It handles type checking and conversion based on the validation mode.
func ValidateWithMode ¶
func ValidateWithMode(data interface{}, schema Schema, mode ValidationMode) error
ValidateWithMode validates data against a schema with a specific validation mode.
Types ¶
type AsyncTransformableSchema ¶ added in v0.3.0
type AsyncTransformableSchema interface {
TransformableSchema
// HasAsyncValidators reports whether this schema has any async validators.
HasAsyncValidators() bool
// ValidateAndTransformAsync runs sync validation and transformations first.
// If sync validation passes, it then runs async validators sequentially.
ValidateAndTransformAsync(goCtx context.Context, value interface{}, ctx *ValidationContext) (interface{}, error)
}
AsyncTransformableSchema represents a schema that supports async validation with transformations. Async validators run only after sync validation passes.
type AsyncValidatorFunc ¶ added in v0.3.0
AsyncValidatorFunc is a function that validates a value asynchronously. It receives a context.Context for cancellation and timeout support, and should return an error if validation fails, nil otherwise. Async validators are only invoked by the async validation methods; sync validation silently ignores them.
type BaseSchema ¶
type BaseSchema struct {
SchemaType SchemaType // Changed from schemaType to SchemaType to make it accessible
// contains filtered or unexported fields
}
BaseSchema provides common functionality for all schema types. It should be embedded in concrete schema implementations.
func (*BaseSchema) AllMeta ¶ added in v0.3.0
func (s *BaseSchema) AllMeta() map[string]interface{}
AllMeta returns all metadata, or nil if none is set.
func (*BaseSchema) CheckRequired ¶
func (s *BaseSchema) CheckRequired(value interface{}, ctx *ValidationContext) bool
CheckRequired checks if a required field is present and not nil. Returns true if validation should continue, false if it should stop.
func (*BaseSchema) GetMeta ¶ added in v0.3.0
func (s *BaseSchema) GetMeta(key string) (interface{}, bool)
GetMeta retrieves metadata by key.
func (*BaseSchema) IsNullable ¶
func (s *BaseSchema) IsNullable() bool
IsNullable returns true if the field can be null.
func (*BaseSchema) IsRequired ¶
func (s *BaseSchema) IsRequired() bool
IsRequired returns true if the field is required.
func (*BaseSchema) SetMeta ¶ added in v0.3.0
func (s *BaseSchema) SetMeta(key string, value interface{})
SetMeta stores a key-value metadata pair. This is the unexported implementation; each builder type exposes a typed Meta() method that calls this and returns itself for chaining.
func (*BaseSchema) SetNullable ¶
func (s *BaseSchema) SetNullable(nullable bool)
SetNullable sets whether the field can be null.
func (*BaseSchema) SetRequired ¶
func (s *BaseSchema) SetRequired(required bool)
SetRequired sets whether the field is required.
type CompiledSchema ¶ added in v0.3.0
type CompiledSchema struct {
BaseSchema
// contains filtered or unexported fields
}
CompiledSchema wraps a Schema with a pre-built flat slice of check functions. All constraint checks (length, range, pattern, enum, custom validators, etc.) are resolved once at compile time and stored as function pointers. At validation time, the compiled schema executes one loop with no nil-checks or conditional branching on which constraints are configured.
func (*CompiledSchema) Inner ¶ added in v0.3.0
func (cs *CompiledSchema) Inner() Schema
Inner returns the original uncompiled schema.
func (*CompiledSchema) Type ¶ added in v0.3.0
func (cs *CompiledSchema) Type() SchemaType
Type returns the underlying schema type.
func (*CompiledSchema) Validate ¶ added in v0.3.0
func (cs *CompiledSchema) Validate(value interface{}, ctx *ValidationContext) error
Validate runs the pre-compiled check chain.
func (*CompiledSchema) ValidateAndTransform ¶ added in v0.3.1
func (cs *CompiledSchema) ValidateAndTransform(value interface{}, ctx *ValidationContext) (interface{}, error)
ValidateAndTransform forwards to the inner schema's transform pipeline when the inner schema is transformable.
type FieldError ¶
type FieldError struct {
// Path is the field path where the error occurred (e.g., "user.email" or "items[0].price")
Path string
// Message describes what validation failed
Message string
// Value is the actual value that failed validation (optional)
Value interface{}
}
FieldError represents a validation error for a specific field.
func NewFieldError ¶
func NewFieldError(path, message string, value interface{}) FieldError
NewFieldError creates a new FieldError.
func (FieldError) Error ¶
func (e FieldError) Error() string
Error implements the error interface for FieldError.
func (FieldError) String ¶
func (e FieldError) String() string
String returns a string representation of the field error.
type Option ¶
type Option func(interface{})
Option represents a configuration option for validators.
type Schema ¶
type Schema interface {
// Validate validates a value against this schema.
// It should add any validation errors to the context.
// Returns an error only for unexpected failures (not validation failures).
Validate(value interface{}, ctx *ValidationContext) error
// Type returns the schema type.
Type() SchemaType
}
Schema represents a validation schema. All schema types must implement this interface.
type SchemaType ¶
type SchemaType string
SchemaType represents the type of a schema.
const ( // TypeString represents a string schema TypeString SchemaType = "string" // TypeNumber represents a number schema TypeNumber SchemaType = "number" // TypeBool represents a boolean schema TypeBool SchemaType = "boolean" // TypeObject represents an object schema TypeObject SchemaType = "object" // TypeArray represents an array schema TypeArray SchemaType = "array" // TypeAny represents a schema that accepts any type TypeAny SchemaType = "any" // TypeCustom represents a custom validator TypeCustom SchemaType = "custom" // TypeComposite represents a composite schema (AND/OR/NOT) TypeComposite SchemaType = "composite" // TypeDateTime represents a date/time schema TypeDateTime SchemaType = "datetime" // TypeDependent represents a dependent field schema TypeDependent SchemaType = "dependent" // TypeTransform represents a transformation schema TypeTransform SchemaType = "transform" )
func (SchemaType) String ¶
func (t SchemaType) String() string
String returns the string representation of a SchemaType.
type TransformableSchema ¶ added in v0.2.0
type TransformableSchema interface {
Schema
// ValidateAndTransform returns the transformed value and any validation error
ValidateAndTransform(value interface{}, ctx *ValidationContext) (interface{}, error)
}
TransformableSchema represents a schema that can apply transformations.
type TransformationRecord ¶ added in v0.2.0
type TransformationRecord struct {
Path string
Original interface{}
Result interface{}
Type string
}
TransformationRecord records a transformation that was applied.
type Transformer ¶ added in v0.2.0
type Transformer interface {
// Transform applies the transformation to a value
Transform(value interface{}) (interface{}, error)
}
Transformer represents a function that can transform values. This is defined here to avoid circular dependencies.
type ValidationContext ¶
type ValidationContext struct {
// contains filtered or unexported fields
}
ValidationContext maintains state during validation. It tracks the current path and accumulates errors.
func NewValidationContext ¶
func NewValidationContext(mode ValidationMode) *ValidationContext
NewValidationContext creates a new validation context.
func (*ValidationContext) AddError ¶
func (c *ValidationContext) AddError(message string, value interface{})
AddError adds an error at the current path.
func (*ValidationContext) AddFieldError ¶
func (c *ValidationContext) AddFieldError(err FieldError)
AddFieldError adds a pre-constructed field error.
func (*ValidationContext) CurrentPath ¶
func (c *ValidationContext) CurrentPath() string
CurrentPath returns the current field path as a string.
func (*ValidationContext) Error ¶
func (c *ValidationContext) Error() error
Error returns a ValidationError if there are any errors, nil otherwise.
func (*ValidationContext) Errors ¶
func (c *ValidationContext) Errors() []FieldError
Errors returns all accumulated errors.
func (*ValidationContext) HasErrors ¶
func (c *ValidationContext) HasErrors() bool
HasErrors returns true if any errors have been added.
func (*ValidationContext) HasTransformations ¶ added in v0.2.0
func (c *ValidationContext) HasTransformations() bool
HasTransformations returns true if any transformations were applied.
func (*ValidationContext) Mode ¶
func (c *ValidationContext) Mode() ValidationMode
Mode returns the validation mode.
func (*ValidationContext) PopPath ¶
func (c *ValidationContext) PopPath()
PopPath removes the last path segment.
func (*ValidationContext) PushIndex ¶
func (c *ValidationContext) PushIndex(index int)
PushIndex adds an array index to the current path.
func (*ValidationContext) PushPath ¶
func (c *ValidationContext) PushPath(segment string)
PushPath adds a path segment to the current path.
func (*ValidationContext) RecordTransformation ¶ added in v0.2.0
func (c *ValidationContext) RecordTransformation(original, result interface{}, transformType string)
RecordTransformation records that a transformation was applied.
func (*ValidationContext) Reset ¶ added in v0.3.0
func (c *ValidationContext) Reset()
Reset clears accumulated errors, path state, and transformation records, allowing the context to be reused across multiple validations without reallocating. The validation mode is preserved.
func (*ValidationContext) Transformations ¶ added in v0.2.0
func (c *ValidationContext) Transformations() []TransformationRecord
Transformations returns all recorded transformations.
func (*ValidationContext) WithIndex ¶
func (c *ValidationContext) WithIndex(index int, fn func())
WithIndex executes a function with an array index pushed onto the context. The index is automatically popped when the function returns.
func (*ValidationContext) WithPath ¶
func (c *ValidationContext) WithPath(segment string, fn func())
WithPath executes a function with a path segment pushed onto the context. The path is automatically popped when the function returns.
type ValidationError ¶
type ValidationError struct {
Errors []FieldError
}
ValidationError represents one or more validation failures. It contains a slice of FieldError that provides detailed information about each validation failure.
func NewValidationError ¶
func NewValidationError(errors ...FieldError) *ValidationError
NewValidationError creates a new ValidationError with the given field errors.
func (*ValidationError) Add ¶
func (e *ValidationError) Add(path, message string, value interface{})
Add adds a field error to the validation error.
func (*ValidationError) AddError ¶
func (e *ValidationError) AddError(err FieldError)
AddError adds an existing FieldError to the validation error.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error returns a string representation of all validation errors.
func (*ValidationError) HasErrors ¶
func (e *ValidationError) HasErrors() bool
HasErrors returns true if there are any validation errors.
type ValidationMode ¶
type ValidationMode int
ValidationMode determines how strict the validation is.
const ( // Strict mode requires exact schema compliance. // Extra fields in objects will cause validation to fail. Strict ValidationMode = iota // Loose mode allows extra fields and safe type coercion. // Extra fields in objects are ignored. // Safe type coercions are applied (e.g., "123" -> 123). Loose )
func (ValidationMode) String ¶
func (m ValidationMode) String() string
String returns the string representation of a ValidationMode.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator wraps a schema with configuration options.
func NewValidator ¶
NewValidator creates a new validator with a schema. The validator can be configured with different modes and options.
type ValidatorFunc ¶
type ValidatorFunc func(value interface{}) error
ValidatorFunc is a function that validates a value. It should return an error if validation fails, nil otherwise.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
datetime.go - Date/Time validation builder for Queryfy
|
datetime.go - Date/Time validation builder for Queryfy |
|
jsonschema
Package jsonschema converts JSON Schema documents into queryfy schemas.
|
Package jsonschema converts JSON Schema documents into queryfy schemas. |
|
transformers
common.go - Common transformation functions
|
common.go - Common transformation functions |
|
examples
|
|
|
basic
command
|
|
|
custom-validators
command
|
|
|
database-validation
command
|
|
|
datetime
command
|
|
|
dependent-fields
command
|
|
|
jsonschema
command
|
|
|
schema-composition
command
|
|
|
transformation-extraction
command
|
|
|
transformation/api
command
|
|
|
transformation/basic
command
|
|
|
transformation/phone
command
|
|
|
Package query provides a simple query language for navigating data structures.
|
Package query provides a simple query language for navigating data structures. |
|
superjsonic
|
|
|
prototype/superjsonic_multi
command
|
|
|
prototype/superjsonic_stress
command
|
|