meta

package
v0.0.0-...-ffb66b1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 10, 2024 License: MIT Imports: 15 Imported by: 3

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ConfigTagFalse = []string{"-"}
View Source
var Defaults = Config{}
View Source
var ForeignTypes = map[string]map[reflect.Type]any{}
View Source
var Postgres = TypeMap{
	From: From{
		"text":     reflect.TypeOf("string"),
		"varchar":  reflect.TypeOf("string"),
		"smallint": reflect.TypeOf(int(1)),
		"int":      reflect.TypeOf(int(1)),
		"bigint":   reflect.TypeOf(int(1)),
	},
	To: To{
		reflect.TypeOf(string("string")): "text",
		reflect.TypeOf(bool(true)):       "boolean",
		reflect.TypeOf(int(1)):           "bigint",
		reflect.TypeOf(int8(1)):          "smallint",
		reflect.TypeOf(int16(1)):         "smallint",
		reflect.TypeOf(int32(1)):         "bigint",
		reflect.TypeOf(int64(1)):         "bigint",
		reflect.TypeOf(float32(1.0)):     "float4",
		reflect.TypeOf(float64(1.0)):     "float8",
		reflect.TypeOf(time.Time{}):      "timestamp with time zone",
		reflect.TypeOf([]byte{}):         "bytea[]",
		// contains filtered or unexported fields
	},
}
View Source
var TemplateDataNames = map[string]string{
	"Struct": "Struct",
}
View Source
var TemplateFuncMap = template.FuncMap{
	"coalesce":      Coalesce[[]string, string],
	"join":          join,
	"joinslices":    JoinSlices,
	"mapkeys":       mapKeys,
	"mapvalues":     mapValues,
	"replace":       replace,
	"replaceall":    replaceAll,
	"tolower":       strings.ToLower,
	"tolowerslices": toLowerSlices,
	"toupper":       strings.ToUpper,
	"toupperslices": toUpperSlices,
	"tostrings":     toStrings,
	"toslice":       toSlice,
	"tovaluemap":    ToValueMap,
}

TemplateFuncMap includes functions in addition to those already included by text/template: https://pkg.go.dev/text/template#hdr-Functions

View Source
var TemplateOptions = []string{
	"missingkey=zero",
}

TemplateOptions is passed to all functions/methods that execute a template.Template see https://pkg.go.dev/text/template#Template.Option

View Source
var TypeMappings = TypeMaps{
	"postgres": Postgres,
}

Functions

func CanSet

func CanSet(a any) bool

func Coalesce

func Coalesce[S []T, T any](first, second S, dflt T) S

Coalesce tries to mimic similar sql functions: it iterates through slices at the same time and returns a slice with the first non-zero value for each element. Unequal length slices are not an issue

func ExpandEnvVars

func ExpandEnvVars(s string) string

ExpandEnvVars substitutes environment variables of the form ${ENV_VAR_NAME} if you have characters that need to be escaped, they should be surrounded in quotes in the source string.

func ExpandFileContents

func ExpandFileContents(s string) string

ExpandFileContents substitutes the placeholder with the contents on the first line of a file. It only accepts the pattern {file:/path/to/file} if you have characters that need to be escaped, they should be surrounded in quotes in the source string.

func Flatten

func Flatten(values any) []any

Flatten is intended for ragged slices that potentially include slices of slices (of slices of slices...) Don't push your luck

func Hack

func Hack(values ...any) []any

func ImplementsInterface

func ImplementsInterface[Reference any](value any) bool

ImplementsInterface is a simple wrapper for checking if a value implements and interface it is primarily useful in switch statements note: Reference must be passed as a type parameter

func IsProcessor

func IsProcessor(a any) bool

func JoinSlices

func JoinSlices(elementSep string, indexSep string, slices ...[]string) string

func Process

func Process(a any) error

func ProcessMap

func ProcessMap(a any) error

ProcessMap is used for dispatching - prefer Process as it will call ProcessMap for any map type that doesn't implement Processor interface

func ProcessRecursively

func ProcessRecursively(a any) error

ProcessRecursively dive's into any member or element processing. It then attempts to call a's Process method, if applicable.

func ProcessSlice

func ProcessSlice(a any) error

ProcessSlice will only attempt to process elements, it won't manage the slice header itself - ie - it will modify or set elements to nil, but will not attempt to grow

func ProcessStruct

func ProcessStruct(a any) error

ProcessStruct doesn't attempt to check/use the struct's Process method.

Instead it iterates through each member and attempts to Process them.

It also makes no effort to process members that are nil pointers or otherwise result in reflect.Kind() == reflect.Invalid.

func RemoveNils

func RemoveNils(values []any) []any

func ToAnySlice

func ToAnySlice[T any](value []T) []any

ToAnySlice converts a slice []T to []any by wrapping each element in interfaces. Useful when you have a concrete slice and need to feed it to something that requires []any.

func ToIndirectReflectValue

func ToIndirectReflectValue(value any) (reflect.Value, reflect.Type, bool)

ToIndirectReflectValue attempts to convert any value to a reflect.Value and indirect it. If value is nil, an invalid reflect.Value, or a nil pointer, the returned value will be invalid. It returns the indrected value and whether the original value was a pointer

func ToSlice

func ToSlice(values ...any) []any

ToSlice should convert a mix of single values and slices to []any, just don't get too tricky

func ToStringSlice

func ToStringSlice(values ...any) []string

Types

type Config

type Config struct {
	NameSpace                []string
	NameSpaceSeparator       string // default is "."
	UUID                     func(any) string
	Tags                     Tags           // struct tags, not field tags, may optionally be parsed from tags labeled struct
	RemoveExistingTags       bool           // remove existing tags - false will simply apopend any included tags to current ones
	Attributes               map[string]any // the kitchen sink... for everything else
	RemoveExistingAttributes bool           // remove existing constraints - false will simply apopend any included constraints to current ones
}

Config allows default config options for various functions Note: this is not yet implemented

type Data

type Data []any

func ToData

func ToData(value any) Data

type Field

type Field struct {
	Name       string
	Attributes map[string]any //string // catchall for additional attributes
	Parent     *Struct
	Value
	reflect.StructField
}

Field is a wrapper for reflect.StructField with some additional functionality for tags, templating, etc.

func (Field) ElementType

func (f Field) ElementType() reflect.Type

ElementType returns the type of an element of a map or slice

func (Field) HasTag

func (f Field) HasTag(keys ...any) bool

HasTag returns true any of the given tag keys exist

func (Field) HasTagFalse

func (f Field) HasTagFalse(keys ...any) bool

HasTagFalse returns true if any Tag satisfies Tags.False

func (Field) HasTagTrue

func (f Field) HasTagTrue(keys ...any) bool

HasTagTrue returns true if its tags satisfy Tags.True

func (Field) HasTagValue

func (f Field) HasTagValue(key, value string) bool

HasTagValue returns true if it has both the key and value

func (Field) Identifier

func (f Field) Identifier() string

Identifier uses the parent's Struct.Identifier and appends the field's Name to it

func (Field) Kind

func (f Field) Kind() reflect.Kind

Kind returns the reflect.Kind. It will first dereference a pointer

func (Field) MultiValued

func (f Field) MultiValued() bool

MultiValued returns true for any 'collection' type or any struct with more than one field

func (Field) NonEmptyTagValue

func (f Field) NonEmptyTagValue(keys ...any) string

func (Field) Pointer

func (f Field) Pointer() bool

Pointer returns true if its reflect.Kind is a reflect.Pointer

func (Field) Tag

func (f Field) Tag(key string) Tag

Tag returns the tag for the given key, according to Tags.Tag

func (Field) TagIdentifier

func (f Field) TagIdentifier(keys ...any) string

TagIdentifier uses the parent's Struct.Identifier and appends the field's Name to it

func (Field) TagName

func (f Field) TagName(keys ...any) string

TagName ranges through the provided keys in order and returns the first non-blank, non-false value, or field.Name if none are found.

func (Field) TagValueAtIndex

func (f Field) TagValueAtIndex(index int, keys ...any) string

TagValueAtIndex returns the first tag.True, non-blank value for keys in the given order. If no match is found, it returns the empty string.

func (Field) Tags

func (f Field) Tags() Tags

Tags returns the parsed struct field tags

func (Field) ToData

func (f Field) ToData() Data

func (Field) ToStruct

func (f Field) ToStruct() (Struct, error)

Converts the element of an Array, Chan, Map, Pointer, or Slice to a Struct. Because it is designed for templating and piping, it panics if it cannot convert the field to a struct

func (Field) Type

func (f Field) Type() reflect.Type

Type returns the reflect.Type. It will first dereference a pointer

type Fields

type Fields []Field

func ToFields

func ToFields(value any) (Fields, error)

func (Fields) ByKinds

func (f Fields) ByKinds(kinds ...reflect.Kind) Fields

func (Fields) ByName

func (f Fields) ByName(name string) Field

func (Fields) ByNames

func (f Fields) ByNames(names ...any) Fields

func (Fields) ByTypes

func (f Fields) ByTypes(types ...reflect.Type) Fields

func (Fields) Field

func (f Fields) Field() Field

Field is a convenience function to avoid having to index in a pipeline. It panics if Fields isn't length 1

func (Fields) Identifiers

func (f Fields) Identifiers() []string

Identifiers returns a slice of the fully namespaced identifiers

func (Fields) Kinds

func (f Fields) Kinds() []reflect.Kind

func (Fields) MultiValued

func (f Fields) MultiValued() Fields

func (Fields) Names

func (f Fields) Names() []string

Names returns a slice of field names

func (Fields) NonEmptyTagValues

func (f Fields) NonEmptyTagValues(keys ...any) []string

NonEmptyTagValues returns a slice of the first non-empty, non-nil tag that satisfies Tag.True and matches a key in the order given. In order to avoid slice length mismatches, it actually does use an empty string for fields where no match is found.

func (Fields) TagIdentifiers

func (f Fields) TagIdentifiers(keys ...any) []string

TagIdentifiers returns a slice of the fully namespaced identifiers from TagIdentifier

func (Fields) TagNames

func (f Fields) TagNames(keys ...any) []string

TagNames returns a slice of the field names according to field.TagName

func (Fields) TagTypeNames

func (f Fields) TagTypeNames(keys ...any) []string

func (Fields) TagTypes

func (f Fields) TagTypes(keys ...any) []string

TagTypes returns the 'type', prefering a tagged value, then falling back to reflect.Type

func (Fields) Tags

func (f Fields) Tags() map[string]Tags

Tags returns a map of Tags with keys that match field names

func (Fields) ToData

func (f Fields) ToData() []Data

func (Fields) ToDataMap

func (f Fields) ToDataMap() map[string]Data

func (Fields) ToStructs

func (f Fields) ToStructs() Structs

ElementsToStructs iterates through each field, attempts to convert it to a Struct, and returns a slice of the valid Structs. Note that it will panic if any field cannot be converted to a struct

func (Fields) TypeNames

func (f Fields) TypeNames() []string

func (Fields) Types

func (f Fields) Types() []reflect.Type

Types returns a slice of field types

func (Fields) WithTag

func (f Fields) WithTag(keys ...any) Fields

WithTag returns a subset of Fields with any of the given keys

func (Fields) WithTagFalse

func (f Fields) WithTagFalse(key string) Fields

WithTagFalse returns a subset of Fields whose Tags satisfy Tags.False

func (Fields) WithTagTrue

func (f Fields) WithTagTrue(keys ...any) Fields

WithTagTrue returns a subset of Fields whose Tags satisfy Tags.True

func (Fields) WithTagValue

func (f Fields) WithTagValue(key, value string) Fields

WithTagValue returns a subset of Fields with both the key and value

func (Fields) WithoutTag

func (f Fields) WithoutTag(keys ...any) Fields

WithoutTag returns a subset of Fields that do not have any of the given keys

func (Fields) WithoutTagValue

func (f Fields) WithoutTagValue(key, value string) Fields

WithoutTagValue returns a subset of Fields that do not have both the key and value

type From

type From map[string]reflect.Type

From is for inbound types - it should map the external system's type name as a key to go's reflect.Type as a value

type Name

type Name struct {
	// contains filtered or unexported fields
}

}

func ParseName

func ParseName(n string, sep string) Name

func ToName

func ToName(n string) Name

func (*Name) SetNamespace

func (n *Name) SetNamespace(ns ...string) Name

func (*Name) SetSeparator

func (n *Name) SetSeparator(sep string) Name

func (Name) String

func (n Name) String() string

type Namespace

type Namespace string

func (Namespace) Join

func (n Namespace) Join(ns ...string) Namespace

func (Namespace) Separator

func (n Namespace) Separator() string

type Processor

type Processor interface {
	Process() error
}

func AsProcessor

func AsProcessor[T any](a T) (Processor, error)

type SQLResult

type SQLResult struct {
	sql.Result
	Values map[string]any
}

type SQLResults

type SQLResults []sql.Result

SQLResults is a slice of sql.Result that also satisfies the sql.Result interface It is intended to allow either merging or maintaining multiple results

func (SQLResults) AddResult

func (r SQLResults) AddResult(results ...sql.Result) SQLResults

func (SQLResults) LastInsertId

func (r SQLResults) LastInsertId() (int64, error)

func (SQLResults) RowsAffected

func (r SQLResults) RowsAffected() (int64, error)

type Struct

type Struct struct {
	Name               string   // default is type (without package namespace), single value children structs default to field name, slices default to type, maps default to key name
	NameSpace          []string // default is []string{"package"}
	NameSpaceSeparator string   // defaults to "."
	Value
	UUID       string
	Attributes map[string]any
	Tags       Tags //map[string][]string
	Parent     *Struct
	Data
}

Struct captures the properties of a struct and allows overriding properties using tags or by direct assignment

func NewStruct

func NewStruct(value any, cfg Structconfig) (Struct, error)

NewStruct enables configuration when parsing a struct to a Struct

func ToStruct

func ToStruct(value any) (Struct, error)

func (*Struct) ExecuteTemplate

func (s *Struct) ExecuteTemplate(tpl string, funcs template.FuncMap, data map[string]any) (string, error)

ExecuteTemplate parses a string and executes it with any additional funcs and data. All data, including the reciever is passed to text/template as a map. By default, the reciever's map key is its type - eg {{ .Struct }} references a calling Struct. By default, it passes missingkey=zero, you can override this by changing TemplateOptions See TemplateFuncMap for additional functions included by default. See TemplateDataNames if you really need to change data map key names.

func (*Struct) Extract

func (s *Struct) Extract(names ...any) map[string]Struct

func (*Struct) ExtractDataByName

func (s *Struct) ExtractDataByName(names ...any) map[string]Data

func (*Struct) Fields

func (s *Struct) Fields() Fields

func (Struct) Identifier

func (s Struct) Identifier() string

Identifier returns the full namespaced identifier of the struct

func (Struct) LastNameSpace

func (s Struct) LastNameSpace() string

func (*Struct) NewUUID

func (s *Struct) NewUUID() string

NewUUID creates a new UUID and sets it recursively

func (*Struct) SetUUID

func (s *Struct) SetUUID(id string)

SetUUID recursively sets s and its fields' struct UUID's to id

func (Struct) TagIdentifier

func (s Struct) TagIdentifier(keys ...any) string

TagIdentifier returns the full namespaced identifier of the struct, but uses TagName instead of Name

func (Struct) TagName

func (s Struct) TagName(keys ...any) string

TagName ranges through the provided keys in order and returns the first non-blank, non-false value, or Struct.Name if none are found.

func (Struct) ValueMap

func (s Struct) ValueMap(tagKey string) ValueMap

type StructWithData

type StructWithData struct {
	Struct
	Data
}

type Structconfig

type Structconfig struct {
	Name                     string
	NameSpace                []string
	NameSpaceSeparator       string // default is "."
	UUID                     string
	Tags                     Tags           // struct tags, not field tags, may optionally be parsed from tags labeled struct
	RemoveExistingTags       bool           // remove existing tags - false will simply apopend any included tags to current ones
	Attributes               map[string]any //string // these should be table constraints, not field constraints
	RemoveExistingAttributes bool           // remove existing constraints - false will simply apopend any included constraints to current ones
	Parent                   *Struct
}

type Structs

type Structs []Struct

func NewStructs

func NewStructs[S []T, T any](value S, cfg Structconfig) Structs

func ToStructs

func ToStructs[S ~[]T, T any](value S) Structs

func (Structs) ExtractDataByName

func (s Structs) ExtractDataByName(names ...any) map[string]Data

func (Structs) Identifiers

func (s Structs) Identifiers() []string

func (Structs) TagName

func (s Structs) TagName(keys ...any) []string

func (Structs) ToStructMap

func (s Structs) ToStructMap() map[string]Struct

type Tag

type Tag []string

func (Tag) AtIndex

func (t Tag) AtIndex(index int) string

AtIndex is a safe alternative to slice indexing. It returns empty string if index is out of bounds or the tag doesn't satify Tag.True

func (Tag) Contains

func (t Tag) Contains(values ...any) bool

Contains is a wrapper for slices.Contains that returns true if the tag contains any of the given values

func (Tag) False

func (t Tag) False() bool

False only returns true if the tag's first value matches one in ConfigTagFalse (by default this is just "-")

func (Tag) Index

func (t Tag) Index(values ...any) int

Index is a wrapper for slices.Index that returns the index of the first value found in the tag, in order given, or -1 if not present

func (Tag) NotContains

func (t Tag) NotContains(values ...any) bool

NotContains is a wrapper for slices.Contains that returns true if the tag doesn't contain any of the given values

func (Tag) True

func (t Tag) True() bool

True returns true if the first value doesn't match one in ConfigTagFalse (by default this is just "-")

type Tags

type Tags map[string]Tag

Tags are the parsed struct field tags as map[tagLabel][]tagvalues

func ToTags

func ToTags(s string) Tags

func (Tags) Append

func (t Tags) Append(key, value string) Tags

Append adds the value to the end of the key's tags it is safe to use even if the key doesn't currently exist

func (Tags) ByKeys

func (t Tags) ByKeys(keys ...any) Tags

ByKeys returns a subset of Tags with the given keys, or nil if none are found

func (Tags) Contains

func (t Tags) Contains(key, value string) bool

Contains returns true if the tag with key has the value, regardless of its index in Tag

func (Tags) Exists

func (t Tags) Exists(keys ...any) bool

Exists returns true if a tag with any of the given keys exists, even if it is empty

func (Tags) False

func (t Tags) False(keys ...any) bool

False only returns true if the tags exists and the first value matches one in ConfigTagFalse (by default this is just "-")

func (Tags) Insert

func (t Tags) Insert(key, value string, index int) Tags

func (Tags) NonEmptyValue

func (t Tags) NonEmptyValue(keys ...any) Tag

NonEmptyValue returns the parsed Tag for the first key found, in order given, where the tag is non-nil, non-empty, and satisfies tag.True. It returns nil if no match is found.

func (Tags) NotContains

func (t Tags) NotContains(key, value string) bool

NotContains returns true if there is no tag with the key and value

func (Tags) Prepend

func (t Tags) Prepend(key, value string) Tags

Prepend inserts the value to the beginning of the key's tags it is safe to use even if the key doesn't currently exist

func (Tags) Replace

func (t Tags) Replace(key, value string, index int) Tags

func (Tags) Set

func (t Tags) Set(key string, values ...string) Tags

Set is a convient method wrapper for assigning (replacing) a key's tags

func (Tags) Tag

func (t Tags) Tag(keys ...any) Tag

Tag returns the tag for key, or nil if it is missing

func (Tags) True

func (t Tags) True(keys ...any) bool

True returns true if the tag exists and the first value does not match one in ConfigTagFalse (by default this is just "-")

func (Tags) Value

func (t Tags) Value(keys ...any) Tag

Value returns the parsed Tag for the first key found, in order given, or nil if missing note: it is currently the same as Tags.Tag but may be changed to return the actual string value

type To

type To map[reflect.Type]string

To is for outbound types - it should map go's reflect.Type as a key to an external type name

type TypeMap

type TypeMap struct {
	From From
	To   To
}

TypeMap combines To/From

func (TypeMap) FromType

func (m TypeMap) FromType(externalType string) reflect.Type

FromType takes the external type and returns the reflect.Type, if it exists in the From typemap

func (TypeMap) ToType

func (m TypeMap) ToType(value any) string

ToType indirects any value and returns the external type as a string, if it exists in the To typemap

type TypeMaps

type TypeMaps map[string]TypeMap

Maps are a collection of external To/From mappings, they should use external system names as keys.

func (TypeMaps) From

func (m TypeMaps) From(system, externalType string) reflect.Type

From returns the go type for the given system/external type, if it exists in the typemap

func (TypeMaps) To

func (m TypeMaps) To(system string, value any) string

To takes any go value and returns the exernal type in the given system, if it exists in the typemap

type UpdateStrategy

type UpdateStrategy int8
const (
	AppendChanges UpdateStrategy = iota
	AppendAll
	ReplaceChanges
	ReplaceAll
)

func (UpdateStrategy) String

func (u UpdateStrategy) String() string

type Value

type Value struct {
	Name string // optional - intended for struct field names, map keys, or slice/array indexes
	reflect.Value
	Pointer bool
	Parent  *Value // only populated if it is a member of a struct or elements of collections - slice, array, map, or channel
}

Value is an attempt to capture a dereferenced reflect.Value. let's hope it works

func ToValue

func ToValue(value any) (Value, error)

ToValue should be able to return a valid Value for anything except a nil pointer or an invalid reflect.Value

func (*Value) Child

func (v *Value) Child(a any) (Value, error)

Child will attempt to return a value's child with the given index/key/field name. It accepts an int for slices, arrays, and structs. It accepts a string for maps and structs.

func (*Value) Children

func (v *Value) Children() []Value

Children returns the elements of slices, arrays, and maps, and the non-anonymous, exported fields of structs if it can be considered a 'child' in some way, it should be returned by this method

func (*Value) ChildrenByIndex

func (v *Value) ChildrenByIndex(index ...any) ([]Value, error)

func (Value) Kind

func (v Value) Kind() reflect.Kind

func (Value) NewElement

func (v Value) NewElement() (Value, error)

NewElement returns a blank element for slices, arrays, maps and channels. For everything else it returns an (invalid) Value and a non-nil error.

func (Value) TypeMap

func (v Value) TypeMap(system string) string

func (Value) Valid

func (v Value) Valid() bool

Valid just wraps reflect.Value.IsValid, because I don't like IsXXX methods unless I really really have to

type ValueMap

type ValueMap map[string]any

ValueMap's keys should match a struct's members' names (or tags) and values are wrapped in any()

func NewValueMap

func NewValueMap(value any, tagKey, excludeValue, includeValue string) ValueMap

NewValueMap is a configurable version of ToValueMap - it converts a struct to a ValueMap based on the given tagKey, excludeValue, and includeValue

func ToValueMap

func ToValueMap(value any, tagKey string) ValueMap

func (ValueMap) Hash

func (v ValueMap) Hash() string

type Values

type Values []Value

func ToValues

func ToValues(a ...any) (Values, error)

func (Values) ByNames

func (v Values) ByNames(names ...string) Values

func (Values) ByTypes

func (v Values) ByTypes(types ...reflect.Type) Values

func (Values) Names

func (v Values) Names() []string

func (Values) Types

func (v Values) Types() []reflect.Type

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL