registry

package
v0.0.0-...-1b52151 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const ANY = "any"

Attribute types

View Source
const ARRAY = "array"
View Source
const BOOLEAN = "boolean"
View Source
const DB_IN = ','

If DB_IN changes then DefaultProps in init.sql needs to change too

View Source
const DB_INDEX = '#'
View Source
const DECIMAL = "decimal"
View Source
const HASDOCUMENT = true
View Source
const INTEGER = "integer"
View Source
const IN_CHAR = '.'
View Source
const IN_STR = string(IN_CHAR)
View Source
const MAP = "map"
View Source
const MAXVERSIONS = 0
View Source
const OBJECT = "object"
View Source
const READONLY = false
View Source
const RegOpt_TrackTimestamps = RegOpt("TRACK_TIMESTAMPS")
View Source
const SETSTICKYDEFAULT = true
View Source
const SETVERSIONID = true
View Source
const SPECVERSION = "0.5"
View Source
const STRICT = true

Model attribute default values

View Source
const STRING = "string"
View Source
const TIMESTAMP = "timestamp"
View Source
const UINTEGER = "uinteger"
View Source
const URI = "uri"
View Source
const URI_REFERENCE = "urireference"
View Source
const URI_TEMPLATE = "uritemplate"
View Source
const URL = "url"
View Source
const UX_IN = '.'
View Source
const XREGSCHEMA = "xRegistry-json"

Variables

View Source
var DB *sql.DB
View Source
var DBHOST = "localhost"
View Source
var DBPASSWORD = "password"
View Source
var DBPORT = "3306"
View Source
var DBUSER = "root"
View Source
var DefaultDiscardWriter = &DiscardWriter{}
View Source
var DefaultRegDbSID string
View Source
var DefinedTypes = map[string]bool{
	ANY:     true,
	BOOLEAN: true,
	DECIMAL: true, INTEGER: true, UINTEGER: true,
	ARRAY:     true,
	MAP:       true,
	OBJECT:    true,
	STRING:    true,
	TIMESTAMP: true,
	URI:       true, URI_REFERENCE: true, URI_TEMPLATE: true, URL: true}
View Source
var JPtrEsc0 = regexp.MustCompile(`~0`)
View Source
var JPtrEsc1 = regexp.MustCompile(`~1`)
View Source
var ModelSerializers = map[string]ModelSerializer{}
View Source
var OrderedSpecProps = []*Attribute{
	{
		Name:           "specversion",
		Type:           STRING,
		ReadOnly:       true,
		Immutable:      true,
		ServerRequired: true,
		// contains filtered or unexported fields
	},
	{
		Name:           "id",
		Type:           STRING,
		Immutable:      true,
		ServerRequired: true,
		// contains filtered or unexported fields
	},
	{
		Name: "name",
		Type: STRING,
		// contains filtered or unexported fields
	},
	{
		Name:           "epoch",
		Type:           UINTEGER,
		ServerRequired: true,
		// contains filtered or unexported fields
	},
	{
		Name:           "self",
		Type:           URL,
		ReadOnly:       true,
		ServerRequired: true,
		// contains filtered or unexported fields
	},
	{
		Name:     "isdefault",
		Type:     BOOLEAN,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name:     "stickydefaultversion",
		Type:     BOOLEAN,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name:     "defaultversionid",
		Type:     STRING,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name:     "defaultversionurl",
		Type:     URL,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name: "description",
		Type: STRING,
		// contains filtered or unexported fields
	},
	{
		Name: "documentation",
		Type: URL,
		// contains filtered or unexported fields
	},
	{
		Name: "labels",
		Type: MAP,
		Item: &Item{
			Type: STRING,
		},
		// contains filtered or unexported fields
	},
	{
		Name: "origin",
		Type: URI,
		// contains filtered or unexported fields
	},
	{
		Name:     "createdby",
		Type:     STRING,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name:     "createdat",
		Type:     TIMESTAMP,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name:     "modifiedby",
		Type:     STRING,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name:     "modifiedat",
		Type:     TIMESTAMP,
		ReadOnly: true,
		// contains filtered or unexported fields
	},
	{
		Name: "contenttype",
		Type: STRING,
		// contains filtered or unexported fields
	},
	{
		Name:     "model",
		Type:     OBJECT,
		ReadOnly: true,
		Attributes: Attributes{
			"*": &Attribute{
				Name: "*",
				Type: ANY,
			},
		},
		// contains filtered or unexported fields
	},
}

This allows for us to choose the order and define custom logic per prop

View Source
var PProfFilter = &FilterPProf{}
View Source
var RegexpMapKey = regexp.MustCompile("^[a-z0-9][a-z0-9_.\\-]{0,62}$")
View Source
var RegexpPropName = regexp.MustCompile("^[a-z_][a-z0-9_./]{0,62}$")
View Source
var SpecProps = map[string]*Attribute{}
View Source
var TESTING = (os.Getenv("TESTING") != "")
View Source
var TXs = map[string]*Tx{}

Active transaction - mainly for debugging and testing

Functions

func AbstractToModels

func AbstractToModels(reg *Registry, abs string) (*GroupModel, *ResourceModel)

func AnyToUInt

func AnyToUInt(val any) (int, error)

func ConvertString

func ConvertString(val string, toType string) (any, bool)

func CopyNewProps

func CopyNewProps(tgt Object, from Object)

func CreateDB

func CreateDB(name string) error

func DBExists

func DBExists(name string) bool

func DeleteDB

func DeleteDB(name string) error

func Do

func Do(tx *Tx, cmd string, args ...interface{}) error

func DoCount

func DoCount(tx *Tx, num int, cmd string, args ...interface{}) error

func DoOne

func DoOne(tx *Tx, cmd string, args ...interface{}) error

func DoOneTwo

func DoOneTwo(tx *Tx, cmd string, args ...interface{}) error

func DoZeroOne

func DoZeroOne(tx *Tx, cmd string, args ...interface{}) error

func DoZeroTwo

func DoZeroTwo(tx *Tx, cmd string, args ...interface{}) error

func DumpTXs

func DumpTXs()

func EnsureAttrOK

func EnsureAttrOK(userAttr *Attribute, specAttr *Attribute) error

Make sure that the attribute doesn't deviate too much from the spec defined version of it. There's only so much that we allow the user to customize

func GenerateQuery

func GenerateQuery(reg *Registry, what string, paths []string, filters [][]*FilterExpr) (string, []interface{}, error)

func GetJSONPointer

func GetJSONPointer(data any, path string) (any, error)

func GetRegistryNames

func GetRegistryNames() []string

func GetStack

func GetStack() []string

func GoToOurType

func GoToOurType(val any) string

func HTMLify

func HTMLify(r *http.Request, buf []byte) []byte

func HTTPDelete

func HTTPDelete(info *RequestInfo) error

func HTTPDeleteGroups

func HTTPDeleteGroups(info *RequestInfo) error

func HTTPDeleteResources

func HTTPDeleteResources(info *RequestInfo) error

func HTTPDeleteVersions

func HTTPDeleteVersions(info *RequestInfo) error

func HTTPGETContent

func HTTPGETContent(info *RequestInfo) error

func HTTPGETModel

func HTTPGETModel(info *RequestInfo) error

func HTTPGet

func HTTPGet(info *RequestInfo) error

func HTTPPUTModel

func HTTPPUTModel(info *RequestInfo) error

func HTTPPutPost

func HTTPPutPost(info *RequestInfo) error

func HTTPSetDefaultVersionID

func HTTPSetDefaultVersionID(info *RequestInfo) error

func ImportTraverse

func ImportTraverse(importArgs ImportArgs, data map[string]any) error

data is the current map to check for $import statements

func IncomingObj2Map

func IncomingObj2Map(incomingObj Object) (map[string]Object, error)

func IsNil

func IsNil(a any) bool

func IsOfType

func IsOfType(val any, attrType string) bool

attr.Type must be a scalar Used to check JSON type vs our types

func IsScalar

func IsScalar(daType string) bool

func IsString

func IsString(daType string) bool

Is some string variant

func IsValidAttributeName

func IsValidAttributeName(name string) bool

func IsValidMapKey

func IsValidMapKey(key string) bool

func JSONEscape

func JSONEscape(obj interface{}) string

func Keys

func Keys(m interface{}) []string

func KindIsScalar

func KindIsScalar(k reflect.Kind) bool

func LineNum

func LineNum(buf []byte, pos int) int

func MaterializeProp

func MaterializeProp(current any, pp *PropPath, val any, prev *PropPath) (any, error)

func Model2xRegistryJson

func Model2xRegistryJson(m *Model, format string) ([]byte, error)

The model serializer we use for the "xRegistry" schema format

func Must

func Must(err error)

func NestedGetProp

func NestedGetProp(obj any, pp *PropPath, prev *PropPath) (any, bool, error)

Value, Found, Error

func NewUUID

func NewUUID() string

func NotNilBoolDef

func NotNilBoolDef(val *any, def bool) bool

func NotNilInt

func NotNilInt(val *any) int

func NotNilIntDef

func NotNilIntDef(val *any, def int) int

func NotNilString

func NotNilString(val *any) string

func ObjectGetProp

func ObjectGetProp(obj any, pp *PropPath) (any, bool, error)

Value, Found, Error

func ObjectSetProp

func ObjectSetProp(obj map[string]any, pp *PropPath, val any) error

func OneLine

func OneLine(buf []byte) []byte

func OpenDB

func OpenDB(name string)

func PanicIf

func PanicIf(b bool, msg string, args ...any)

func Panicf

func Panicf(msg string, args ...any)

func Path2Abstract

func Path2Abstract(path string) string

func PrepUpdateEntity

func PrepUpdateEntity(e *Entity) error

func ProcessImports

func ProcessImports(file string, buf []byte, localFiles bool) ([]byte, error)

func ProcessSetDefaultVersionIDFlag

func ProcessSetDefaultVersionIDFlag(info *RequestInfo, resource *Resource, version *Version) error

Process the ?setdefaultversionid query parameter "resource" is the resource we're processing "version" is the version that was processed

func PtrBool

func PtrBool(b bool) *bool

func PtrBoolDef

func PtrBoolDef(val *any, def bool) *bool

func PtrIntDef

func PtrIntDef(val *any, def int) *int

func RegHTMLify

func RegHTMLify(r *http.Request, buf []byte) []byte

func RegisterModelSerializer

func RegisterModelSerializer(name string, sm ModelSerializer)

func RemoveComments

func RemoveComments(buf []byte) []byte

func RemoveProps

func RemoveProps(buf []byte) []byte

func ResetMap

func ResetMap[M ~map[K]V, K comparable, V any](m M, key K, oldVal V)

Either delete or change the value of a map based on "oldVal" being nil or not

func ResolvePath

func ResolvePath(baseFile string, next string) string

func SerializeQuery

func SerializeQuery(info *RequestInfo, paths []string, what string,
	filters [][]*FilterExpr) error

func ShowStack

func ShowStack()

func SortedKeys

func SortedKeys(m interface{}) []string

func SplitFragement

func SplitFragement(str string) (string, string)

func SubQuery

func SubQuery(query string, args []interface{}) string

func ToJSON

func ToJSON(obj interface{}) string

func ToJSONOneLine

func ToJSONOneLine(obj interface{}) string

func Unmarshal

func Unmarshal(buf []byte, v any) error

Types

type AttrInternals

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

Defined a separate struct instead of just inlining these attributes so that we can just copy them over in one statement in SetSpecPropsFields() and so that if we add more we don't need to remember to update that func

type Attribute

type Attribute struct {
	Registry       *Registry `json:"-"`
	Name           string    `json:"name,omitempty"`
	Type           string    `json:"type,omitempty"`
	Description    string    `json:"description,omitempty"`
	Enum           []any     `json:"enum,omitempty"` // just scalars though
	Strict         *bool     `json:"strict,omitempty"`
	ReadOnly       bool      `json:"readonly,omitempty"`
	Immutable      bool      `json:"immutable,omitempty"`
	ClientRequired bool      `json:"clientrequired,omitempty"`
	ServerRequired bool      `json:"serverrequired,omitempty"`
	Default        any       `json:"default,omitempty"`

	Attributes Attributes `json:"attributes,omitempty"` // for Objs
	Item       *Item      `json:"item,omitempty"`       // for maps & arrays
	IfValues   IfValues   `json:"ifValues,omitempty"`   // Value
	// contains filtered or unexported fields
}

Do not include "omitempty" on any attribute that has a default value that doesn't match golang's default value for that type. E.g. bool defaults to 'false', but Strict needs to default to 'true'. See the custome Unmarshal funcs in model.go for how we set those

func (*Attribute) AddAttr

func (a *Attribute) AddAttr(name, daType string) (*Attribute, error)

func (*Attribute) AddAttrArray

func (a *Attribute) AddAttrArray(name string, item *Item) (*Attribute, error)

func (*Attribute) AddAttrMap

func (a *Attribute) AddAttrMap(name string, item *Item) (*Attribute, error)

func (*Attribute) AddAttrObj

func (a *Attribute) AddAttrObj(name string) (*Attribute, error)

func (*Attribute) AddAttribute

func (a *Attribute) AddAttribute(attr *Attribute) (*Attribute, error)

func (*Attribute) GetStrict

func (a *Attribute) GetStrict() bool

func (*Attribute) InLevel

func (a *Attribute) InLevel(level int) bool

func (*Attribute) IsScalar

func (a *Attribute) IsScalar() bool

func (*Attribute) SetRegistry

func (a *Attribute) SetRegistry(reg *Registry)

type Attributes

type Attributes map[string]*Attribute // AttrName->Attr

func (Attributes) AddIfValuesAttributes

func (attrs Attributes) AddIfValuesAttributes(obj map[string]any)

This just does the top-level attributes with the assumption that we'll do the lower-level ones later on in Entity.ValidateObject

func (Attributes) ConvertStrings

func (attrs Attributes) ConvertStrings(obj Object)

func (Attributes) MarshalJSON

func (attrs Attributes) MarshalJSON() ([]byte, error)

To be picky, let's Marshal the list of attributes with Spec defined ones first, and then the extensions in alphabetical order

func (Attributes) SetRegistry

func (attrs Attributes) SetRegistry(reg *Registry)

func (Attributes) SetSpecPropsFields

func (attrs Attributes) SetSpecPropsFields()

Copy the internal data for spec defined properties so we can access that info directly from these Attributes instead of having to go back to the SpecProps stuff

func (Attributes) Verify

func (attrs Attributes) Verify(ld *LevelData) error

type BufferedWriter

type BufferedWriter struct {
	Info      *RequestInfo
	OldWriter HTTPWriter
	Headers   *map[string]string
	Buffer    *bytes.Buffer
}

func NewBufferedWriter

func NewBufferedWriter(info *RequestInfo) *BufferedWriter

func (*BufferedWriter) AddHeader

func (bw *BufferedWriter) AddHeader(name, value string)

func (*BufferedWriter) Done

func (bw *BufferedWriter) Done()

func (*BufferedWriter) Write

func (bw *BufferedWriter) Write(b []byte) (int, error)

type DefaultWriter

type DefaultWriter struct {
	Info *RequestInfo
}

func (*DefaultWriter) AddHeader

func (dw *DefaultWriter) AddHeader(name, value string)

func (*DefaultWriter) Done

func (dw *DefaultWriter) Done()

func (*DefaultWriter) Write

func (dw *DefaultWriter) Write(b []byte) (int, error)

type DiscardWriter

type DiscardWriter struct{}

func (*DiscardWriter) AddHeader

func (dw *DiscardWriter) AddHeader(name, value string)

func (*DiscardWriter) Done

func (dw *DiscardWriter) Done()

func (*DiscardWriter) Write

func (dw *DiscardWriter) Write(b []byte) (int, error)

type Entity

type Entity struct {
	Registry  *Registry `json:"-"`
	DbSID     string    // Entity's SID
	Plural    string
	UID       string         // Entity's UID
	Object    map[string]any `json:"-"`
	NewObject map[string]any `json:"-"` // updated version, save() will store

	// These were added just for convenience and so we can use the same
	// struct for traversing the SQL results
	Level    int // 0=registry, 1=group, 2=resource, 3=version
	Path     string
	Abstract string
	EpochSet bool `json:"-"` // Has epoch been updated this transaction?
	// contains filtered or unexported fields
}

func RawEntitiesFromQuery

func RawEntitiesFromQuery(tx *Tx, regID string, query string, args ...any) ([]*Entity, error)

func RawEntityFromPath

func RawEntityFromPath(tx *Tx, regID string, path string) (*Entity, error)

func (*Entity) Get

func (e *Entity) Get(path string) any

func (*Entity) GetAttributes

func (e *Entity) GetAttributes(obj Object) Attributes

func (*Entity) GetBaseAttributes

func (e *Entity) GetBaseAttributes() Attributes

Returns the initial set of attributes defined for the entity.

func (*Entity) GetCollections

func (e *Entity) GetCollections() []string

func (*Entity) GetModels

func (e *Entity) GetModels() (*GroupModel, *ResourceModel)

func (*Entity) GetPP

func (e *Entity) GetPP(pp *PropPath) any

func (*Entity) JustSet

func (e *Entity) JustSet(pp *PropPath, val any) error

Set the prop in the Entity but don't Validate or Save to the DB

func (*Entity) Materialize

func (e *Entity) Materialize(info *RequestInfo) map[string]any

Note that this will copy the default version props to the resource. This is mainly used for end-user facing serialization of the entity

func (*Entity) Refresh

func (e *Entity) Refresh() error

Update the entity's Object - not the other props in Entity. Similar to RawEntityFromPath

func (*Entity) RemoveCollections

func (e *Entity) RemoveCollections(obj Object)

This will remove all Collection related attributes from the entity. While this is an Entity.Func, we allow callers to pass in the Object data to use instead of the e.Object/NewObject so that we'll use this Entity's Level (which tells us which collections it has), on the 'obj'. This is handy for cases where we need to remove the Resource's collections from a Version's Object - like on a PUT to /GROUPs/gID/RESOURECEs/rID where we're passing in what looks like a Resource entity, but we're really using it to create a Version

func (*Entity) Save

func (e *Entity) Save() error

func (*Entity) SerializeProps

func (e *Entity) SerializeProps(info *RequestInfo,
	fn func(*Entity, *RequestInfo, string, any, *Attribute) error) error

This is used to serialize an Entity regardless of the format. This will:

  • Use Materialize() to fill in any missing props (eg Entity's getFn()) as well as fully materialize a Resource from its default Version
  • Call that passed-in 'fn' to serialize each prop but in the right order as defined by OrderedSpecProps

func (*Entity) SetCommit

func (e *Entity) SetCommit(path string, val any) error

All in one: Set, Validate, Save to DB and Commit (or Rollback on error) Should never be used because the act of committing should be done by the caller once all of the changes are done. This is a holdover from before we had transaction support - once we're sure, delete it

func (*Entity) SetDBProperty

func (e *Entity) SetDBProperty(pp *PropPath, val any) error

This will save a single property/value in the DB. This assumes the caller is traversing the Object and splitting it into individual props

func (*Entity) SetFromDBName

func (e *Entity) SetFromDBName(name string, val *string, propType string) error

This is used to take a DB entry and update the current Entity's Object

func (*Entity) SetPP

func (e *Entity) SetPP(pp *PropPath, val any) error

This is really just an internal Setter used for testing. It'sll set a property and then validate and save the entity in the DB

func (*Entity) SetSave

func (e *Entity) SetSave(path string, val any) error

Set, Validate and Save to DB but not Commit

func (*Entity) Validate

func (e *Entity) Validate() error

Doesn't fully validate in the sense that it'll assume read-only fields are not worth checking since the server generated them. This is mainly used for validating input from a client. NOTE!!! This isn't a read-only operation. Normally it would be, but to avoid traversing the entity more than once, we will tweak things if needed. For example, if a missing attribute has a Default value then we'll add it.

func (*Entity) ValidateAndSave

func (e *Entity) ValidateAndSave() error

func (*Entity) ValidateArray

func (e *Entity) ValidateArray(val any, item *Item, path *PropPath) error

func (*Entity) ValidateAttribute

func (e *Entity) ValidateAttribute(val any, attr *Attribute, path *PropPath) error

func (*Entity) ValidateMap

func (e *Entity) ValidateMap(val any, item *Item, path *PropPath) error

func (*Entity) ValidateObject

func (e *Entity) ValidateObject(val any, origAttrs Attributes, path *PropPath) error

This should be called after all level-specific calculated properties have been removed - such as collections

func (*Entity) ValidateScalar

func (e *Entity) ValidateScalar(val any, attr *Attribute, path *PropPath) error

type EntitySetter

type EntitySetter interface {
	Get(name string) any
	SetCommit(name string, val any) error // Should never be used
	SetSave(name string, val any) error
}

type FilterExpr

type FilterExpr struct {
	Path     string // endpoints.id  TODO store a PropPath?
	Value    string // myEndpoint
	HasEqual bool
}

type FilterPProf

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

func (*FilterPProf) Write

func (fp *FilterPProf) Write(p []byte) (n int, err error)

When dumping all processes, filter out the ones that aren't running our code and only show lines of interest to keep it small

type Group

type Group struct {
	Entity
	Registry *Registry
}

func (*Group) AddResource

func (g *Group) AddResource(rType string, id string, vID string) (*Resource, error)

func (*Group) AddResourceWithObject

func (g *Group) AddResourceWithObject(rType string, id string, vID string, obj Object) (*Resource, error)

func (*Group) Delete

func (g *Group) Delete() error

func (*Group) FindResource

func (g *Group) FindResource(rType string, id string) (*Resource, error)

func (*Group) Get

func (g *Group) Get(name string) any

func (*Group) JustSet

func (g *Group) JustSet(name string, val any) error

func (*Group) SetCommit

func (g *Group) SetCommit(name string, val any) error

func (*Group) SetSave

func (g *Group) SetSave(name string, val any) error

func (*Group) UpsertResource

func (g *Group) UpsertResource(rType string, id string, vID string) (*Resource, bool, error)

func (*Group) UpsertResourceWithObject

func (g *Group) UpsertResourceWithObject(rType string, id string, vID string, obj Object) (*Resource, bool, error)

type GroupModel

type GroupModel struct {
	SID      string    `json:"-"`
	Registry *Registry `json:"-"`

	Plural     string     `json:"plural"`
	Singular   string     `json:"singular"`
	Attributes Attributes `json:"attributes,omitempty"`

	Resources map[string]*ResourceModel `json:"resources,omitempty"` // Plural
}

func (*GroupModel) AddAttr

func (gm *GroupModel) AddAttr(name, daType string) (*Attribute, error)

func (*GroupModel) AddAttrArray

func (gm *GroupModel) AddAttrArray(name string, item *Item) (*Attribute, error)

func (*GroupModel) AddAttrMap

func (gm *GroupModel) AddAttrMap(name string, item *Item) (*Attribute, error)

func (*GroupModel) AddAttrObj

func (gm *GroupModel) AddAttrObj(name string) (*Attribute, error)

func (*GroupModel) AddAttribute

func (gm *GroupModel) AddAttribute(attr *Attribute) (*Attribute, error)

func (*GroupModel) AddResourceModel

func (gm *GroupModel) AddResourceModel(plural string, singular string, maxVersions int, setVerId bool, setStickyDefault bool, hasDocument bool) (*ResourceModel, error)

func (*GroupModel) AddResourceModelFull

func (gm *GroupModel) AddResourceModelFull(rm *ResourceModel) (*ResourceModel, error)

func (*GroupModel) AddResourceModelSimple

func (gm *GroupModel) AddResourceModelSimple(plural, singular string) (*ResourceModel, error)

func (*GroupModel) DelAttribute

func (gm *GroupModel) DelAttribute(name string) error

func (*GroupModel) Delete

func (gm *GroupModel) Delete() error

func (*GroupModel) GetBaseAttributes

func (gm *GroupModel) GetBaseAttributes() Attributes

func (*GroupModel) Save

func (gm *GroupModel) Save() error

func (*GroupModel) SetRegistry

func (gm *GroupModel) SetRegistry(reg *Registry)

func (*GroupModel) Verify

func (gm *GroupModel) Verify(gmName string) error

type HTTPWriter

type HTTPWriter interface {
	Write([]byte) (int, error)
	AddHeader(string, string)
	Done()
}

func DefaultHTTPWriter

func DefaultHTTPWriter(info *RequestInfo) HTTPWriter

type IDArray

type IDArray []IDEntry

func LoadIDList

func LoadIDList(info *RequestInfo) (IDArray, error)

type IDEntry

type IDEntry struct {
	ID    string
	Epoch *int
}

type IfValue

type IfValue struct {
	SiblingAttributes Attributes `json:"siblingAttributes,omitempty"`
}

type IfValues

type IfValues map[string]*IfValue

func (IfValues) SetRegistry

func (ifvalues IfValues) SetRegistry(reg *Registry)

type ImportArgs

type ImportArgs struct {
	// Cache path/name of "" means stdin
	Cache      map[string]map[string]any // Path#.. -> json
	History    []string                  // Just names, no frag, [0]=latest
	LocalFiles bool                      // ok to access local FS files?
}

type Item

type Item struct {
	Registry   *Registry  `json:"-"`
	Type       string     `json:"type,omitempty"`
	Attributes Attributes `json:"attributes,omitempty"` // when 'type'=obj
	Item       *Item      `json:"item,omitempty"`       // when 'type'=map,array
}

func NewItem

func NewItem() *Item

func NewItemArray

func NewItemArray(item *Item) *Item

func NewItemMap

func NewItemMap(item *Item) *Item

func NewItemObject

func NewItemObject() *Item

func NewItemType

func NewItemType(daType string) *Item

func (*Item) AddAttr

func (i *Item) AddAttr(name, daType string) (*Attribute, error)

func (*Item) AddAttrArray

func (i *Item) AddAttrArray(name string, item *Item) (*Attribute, error)

func (*Item) AddAttrMap

func (i *Item) AddAttrMap(name string, item *Item) (*Attribute, error)

func (*Item) AddAttrObj

func (i *Item) AddAttrObj(name string) (*Attribute, error)

func (*Item) AddAttribute

func (i *Item) AddAttribute(attr *Attribute) (*Attribute, error)

func (*Item) DelAttribute

func (i *Item) DelAttribute(name string) error

func (*Item) SetItem

func (i *Item) SetItem(item *Item) error

func (*Item) SetRegistry

func (i *Item) SetRegistry(reg *Registry)

func (*Item) Verify

func (item *Item) Verify(path *PropPath) error

type JsonWriter

type JsonWriter struct {
	Entity *Entity // Current row in the DB results
	// contains filtered or unexported fields
}

func NewJsonWriter

func NewJsonWriter(info *RequestInfo, results *Result) *JsonWriter

func (*JsonWriter) Indent

func (jw *JsonWriter) Indent()

func (*JsonWriter) LoadCollections

func (jw *JsonWriter) LoadCollections(level int)

func (*JsonWriter) NextEntity

func (jw *JsonWriter) NextEntity() (*Entity, error)

func (*JsonWriter) OptPrintf

func (jw *JsonWriter) OptPrintf(format string, args ...any)

func (*JsonWriter) Outdent

func (jw *JsonWriter) Outdent()

func (*JsonWriter) Print

func (jw *JsonWriter) Print(str string)

func (*JsonWriter) Printf

func (jw *JsonWriter) Printf(format string, args ...any)

func (*JsonWriter) WriteCollection

func (jw *JsonWriter) WriteCollection() (int, error)

func (*JsonWriter) WriteCollectionHeader

func (jw *JsonWriter) WriteCollectionHeader(extra string) (string, error)

func (*JsonWriter) WriteEntity

func (jw *JsonWriter) WriteEntity() error

func (*JsonWriter) WritePostCollections

func (jw *JsonWriter) WritePostCollections(extra string, level int) string

func (*JsonWriter) WritePreCollections

func (jw *JsonWriter) WritePreCollections(extra string, plural string, level int) string

type LevelData

type LevelData struct {
	// AttrNames is the list of known attribute names for a certain level
	// an entity (basically the Attributes list + ifValues). We use this to know
	// if an IfValue SiblingAttribute would conflict if another attribute's name
	AttrNames map[string]bool
	Path      *PropPath
}

type Model

type Model struct {
	Registry   *Registry              `json:"-"`
	Schemas    []string               `json:"schemas,omitempty"`
	Attributes Attributes             `json:"attributes,omitempty"`
	Groups     map[string]*GroupModel `json:"groups,omitempty"` // Plural
}

func LoadModel

func LoadModel(reg *Registry) *Model

func (*Model) AddAttr

func (m *Model) AddAttr(name, daType string) (*Attribute, error)

func (*Model) AddAttrArray

func (m *Model) AddAttrArray(name string, item *Item) (*Attribute, error)

func (*Model) AddAttrMap

func (m *Model) AddAttrMap(name string, item *Item) (*Attribute, error)

func (*Model) AddAttrObj

func (m *Model) AddAttrObj(name string) (*Attribute, error)

func (*Model) AddAttribute

func (m *Model) AddAttribute(attr *Attribute) (*Attribute, error)

func (*Model) AddGroupModel

func (m *Model) AddGroupModel(plural string, singular string) (*GroupModel, error)

func (*Model) AddSchema

func (m *Model) AddSchema(schema string) error

func (*Model) ApplyNewModel

func (m *Model) ApplyNewModel(newM *Model) error

func (*Model) DelAttribute

func (m *Model) DelAttribute(name string) error

func (*Model) DelSchema

func (m *Model) DelSchema(schema string) error

func (*Model) FindGroupModel

func (m *Model) FindGroupModel(gTypePlural string) *GroupModel

func (*Model) GetBaseAttributes

func (m *Model) GetBaseAttributes() Attributes

func (*Model) Save

func (m *Model) Save() error

func (*Model) SetPointers

func (m *Model) SetPointers()

func (*Model) SetSchemas

func (m *Model) SetSchemas(schemas []string) error

func (*Model) Verify

func (m *Model) Verify() error

func (*Model) VerifyAndSave

func (m *Model) VerifyAndSave() error

VerifyAndSave() should be called by automatically but there may be cases where someone would need to call it manually (e.g. setting an attribute's property - we should technically find a way to catch those cases so code above this shouldn't need to think about it

type ModelSerializer

type ModelSerializer func(*Model, string) ([]byte, error)

func GetModelSerializer

func GetModelSerializer(format string) ModelSerializer

type Object

type Object map[string]any

func ExtractIncomingObject

func ExtractIncomingObject(info *RequestInfo, body []byte) (Object, error)

type PageWriter

type PageWriter struct {
	Info      *RequestInfo
	OldWriter HTTPWriter
	Headers   *map[string]string
	Buffer    *bytes.Buffer
}

func NewPageWriter

func NewPageWriter(info *RequestInfo) *PageWriter

func (*PageWriter) AddHeader

func (pw *PageWriter) AddHeader(name, value string)

func (*PageWriter) Done

func (pw *PageWriter) Done()

func (*PageWriter) Write

func (pw *PageWriter) Write(b []byte) (int, error)

type PropPart

type PropPart struct {
	Text  string
	Index int
}

func (*PropPart) ToInt

func (pp *PropPart) ToInt() int

type PropPath

type PropPath struct {
	Parts []PropPart
}

func MustPropPathFromDB

func MustPropPathFromDB(str string) *PropPath

func NewPP

func NewPP() *PropPath

func NewPPP

func NewPPP(prop string) *PropPath

func PropPathFromDB

func PropPathFromDB(str string) (*PropPath, error)

func PropPathFromPath

func PropPathFromPath(str string) (*PropPath, error)

func PropPathFromUI

func PropPathFromUI(str string) (*PropPath, error)

func (*PropPath) Abstract

func (pp *PropPath) Abstract() string

func (*PropPath) Append

func (pp *PropPath) Append(addPP *PropPath) *PropPath

func (*PropPath) Clone

func (pp *PropPath) Clone() *PropPath

func (*PropPath) DB

func (pp *PropPath) DB() string

func (*PropPath) Equals

func (pp *PropPath) Equals(other *PropPath) bool

func (*PropPath) First

func (pp *PropPath) First() *PropPath

func (*PropPath) HasPrefix

func (pp *PropPath) HasPrefix(other *PropPath) bool

func (*PropPath) I

func (pp *PropPath) I(i int) *PropPath

func (*PropPath) Index

func (pp *PropPath) Index(i int) *PropPath

func (*PropPath) IsIndexed

func (pp *PropPath) IsIndexed() int

func (*PropPath) Len

func (pp *PropPath) Len() int

func (*PropPath) Next

func (pp *PropPath) Next() *PropPath

func (*PropPath) P

func (pp *PropPath) P(prop string) *PropPath

func (*PropPath) Path

func (pp *PropPath) Path() string

func (*PropPath) Prop

func (pp *PropPath) Prop(prop string) *PropPath

func (*PropPath) Top

func (pp *PropPath) Top() string

func (*PropPath) UI

func (pp *PropPath) UI() string

type RegOpt

type RegOpt string

type Registry

type Registry struct {
	Entity
	Model *Model
}

func FindRegistry

func FindRegistry(tx *Tx, id string) (*Registry, error)

BY UID

func FindRegistryBySID

func FindRegistryBySID(tx *Tx, sid string) (*Registry, error)

func GetDefaultReg

func GetDefaultReg(tx *Tx) *Registry

func NewRegistry

func NewRegistry(tx *Tx, id string, regOpts ...RegOpt) (*Registry, error)

func (*Registry) AddGroup

func (reg *Registry) AddGroup(gType string, id string) (*Group, error)

func (*Registry) AddGroupWithObject

func (reg *Registry) AddGroupWithObject(gType string, id string, obj Object) (*Group, error)

func (*Registry) Commit

func (r *Registry) Commit() error

func (*Registry) Delete

func (reg *Registry) Delete() error

func (*Registry) FindGroup

func (reg *Registry) FindGroup(gType string, id string) (*Group, error)

func (*Registry) Get

func (reg *Registry) Get(name string) any

func (*Registry) JustSet

func (reg *Registry) JustSet(name string, val any) error

func (*Registry) LoadModel

func (reg *Registry) LoadModel() *Model

func (*Registry) LoadModelFromFile

func (reg *Registry) LoadModelFromFile(file string) error

func (*Registry) Rollback

func (r *Registry) Rollback() error

func (*Registry) SetCommit

func (reg *Registry) SetCommit(name string, val any) error

Technically this should be called SetValidateSave

func (*Registry) SetSave

func (reg *Registry) SetSave(name string, val any) error

func (*Registry) TrackTimestamps

func (reg *Registry) TrackTimestamps(val bool) error

func (*Registry) UpsertGroup

func (reg *Registry) UpsertGroup(gType string, id string) (*Group, bool, error)

func (*Registry) UpsertGroupWithObject

func (reg *Registry) UpsertGroupWithObject(gType string, id string, obj Object) (*Group, bool, error)

type RequestInfo

type RequestInfo struct {
	Registry         *Registry
	BaseURL          string
	OriginalPath     string
	OriginalRequest  *http.Request       `json:"-"`
	OriginalResponse http.ResponseWriter `json:"-"`
	Parts            []string
	Root             string
	Abstract         string
	GroupType        string
	GroupUID         string
	GroupModel       *GroupModel
	ResourceType     string
	ResourceUID      string
	ResourceModel    *ResourceModel
	VersionUID       string
	What             string          // Registry, Coll, Entity
	Inlines          []string        // TODO store a PropPaths instead
	Filters          [][]*FilterExpr // [OR][AND] filter=e,e(and) &(or) filter=e
	ShowModel        bool
	ShowMeta         bool

	StatusCode int
	SentStatus bool
	HTTPWriter HTTPWriter `json:"-"`
	// contains filtered or unexported fields
}

func ParseRequest

func ParseRequest(tx *Tx, w http.ResponseWriter, r *http.Request) (*RequestInfo, error)

func (*RequestInfo) AddHeader

func (ri *RequestInfo) AddHeader(name, value string)

func (*RequestInfo) AddInline

func (info *RequestInfo) AddInline(path string) error

func (*RequestInfo) ParseFilters

func (info *RequestInfo) ParseFilters() error

func (*RequestInfo) ParseRequestURL

func (info *RequestInfo) ParseRequestURL() error

func (*RequestInfo) ShouldInline

func (info *RequestInfo) ShouldInline(entityPath string) bool

func (*RequestInfo) Write

func (ri *RequestInfo) Write(b []byte) (int, error)

type Resource

type Resource struct {
	Entity
	Group *Group
}

func (*Resource) AddVersion

func (r *Resource) AddVersion(id string) (*Version, error)

func (*Resource) AddVersionWithObject

func (r *Resource) AddVersionWithObject(id string, obj Object) (*Version, error)

func (*Resource) Delete

func (r *Resource) Delete() error

func (*Resource) EnsureMaxVersions

func (r *Resource) EnsureMaxVersions() error

func (*Resource) FindVersion

func (r *Resource) FindVersion(id string) (*Version, error)

Maybe replace error with a panic? same for other finds??

func (*Resource) Get

func (r *Resource) Get(name string) any

func (*Resource) GetDefault

func (r *Resource) GetDefault() (*Version, error)

Maybe replace error with a panic?

func (*Resource) GetVersionIDs

func (r *Resource) GetVersionIDs() ([]string, error)

func (*Resource) GetVersions

func (r *Resource) GetVersions() ([]*Version, error)

func (*Resource) JustSet

func (r *Resource) JustSet(name string, val any) error

func (*Resource) SetCommit

func (r *Resource) SetCommit(name string, val any) error

func (*Resource) SetDefault

func (r *Resource) SetDefault(newDefault *Version) error

Only call this if you want things to be sticky (when not nil). Creating a new version should do this directly

func (*Resource) SetSave

func (r *Resource) SetSave(name string, val any) error

func (*Resource) UpsertVersion

func (r *Resource) UpsertVersion(id string) (*Version, bool, error)

func (*Resource) UpsertVersionWithObject

func (r *Resource) UpsertVersionWithObject(id string, obj Object) (*Version, bool, error)

type ResourceModel

type ResourceModel struct {
	SID        string      `json:"-"`
	GroupModel *GroupModel `json:"-"`

	Plural           string     `json:"plural"`
	Singular         string     `json:"singular"`
	MaxVersions      int        `json:"maxversions"`             // do not include omitempty
	SetVersionId     *bool      `json:"setversionid"`            // do not include omitempty
	SetStickyDefault *bool      `json:"setstickydefaultversion"` // do not include omitempty
	HasDocument      *bool      `json:"hasdocument"`             // do not include omitempty
	ReadOnly         bool       `json:"readonly,omitempty"`
	Attributes       Attributes `json:"attributes,omitempty"`
}

func (*ResourceModel) AddAttr

func (rm *ResourceModel) AddAttr(name, daType string) (*Attribute, error)

func (*ResourceModel) AddAttrArray

func (rm *ResourceModel) AddAttrArray(name string, item *Item) (*Attribute, error)

func (*ResourceModel) AddAttrMap

func (rm *ResourceModel) AddAttrMap(name string, item *Item) (*Attribute, error)

func (*ResourceModel) AddAttrObj

func (rm *ResourceModel) AddAttrObj(name string) (*Attribute, error)

func (*ResourceModel) AddAttribute

func (rm *ResourceModel) AddAttribute(attr *Attribute) (*Attribute, error)

func (*ResourceModel) DelAttribute

func (rm *ResourceModel) DelAttribute(name string) error

func (*ResourceModel) Delete

func (rm *ResourceModel) Delete() error

func (*ResourceModel) GetBaseAttributes

func (rm *ResourceModel) GetBaseAttributes() Attributes

func (*ResourceModel) GetHasDocument

func (rm *ResourceModel) GetHasDocument() bool

func (*ResourceModel) GetSetStickyDefault

func (rm *ResourceModel) GetSetStickyDefault() bool

func (*ResourceModel) GetSetVersionId

func (rm *ResourceModel) GetSetVersionId() bool

func (*ResourceModel) Save

func (rm *ResourceModel) Save() error

func (*ResourceModel) SetMaxVersions

func (rm *ResourceModel) SetMaxVersions(maxV int) error

func (*ResourceModel) SetRegistry

func (rm *ResourceModel) SetRegistry(reg *Registry)

func (*ResourceModel) SetSetStickyDefault

func (rm *ResourceModel) SetSetStickyDefault(val bool) error

func (*ResourceModel) UnmarshalJSON

func (r *ResourceModel) UnmarshalJSON(data []byte) error

func (*ResourceModel) Verify

func (rm *ResourceModel) Verify(rmName string) error

func (*ResourceModel) VerifyAndSave

func (rm *ResourceModel) VerifyAndSave() error

func (*ResourceModel) VerifyData

func (rm *ResourceModel) VerifyData() error

type Result

type Result struct {
	Data     []*any // One row
	TempData []any
	Reuse    bool

	AllRows [][]*any
	// contains filtered or unexported fields
}

func Query

func Query(tx *Tx, cmd string, args ...interface{}) (*Result, error)

func (*Result) Close

func (r *Result) Close()

func (*Result) NextRow

func (r *Result) NextRow() []*any

func (*Result) PullNextRow

func (r *Result) PullNextRow()

func (*Result) Push

func (r *Result) Push()

func (*Result) RetrieveAllRowsFromDB

func (r *Result) RetrieveAllRowsFromDB()

func (*Result) RetrieveNextRowFromDB

func (r *Result) RetrieveNextRowFromDB() bool

type Server

type Server struct {
	Port       int
	HTTPServer *http.Server
}

func NewServer

func NewServer(port int) *Server

func (*Server) Close

func (s *Server) Close()

func (*Server) Serve

func (s *Server) Serve()

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) Start

func (s *Server) Start() *Server

type Tx

type Tx struct {
	Registry   *Registry
	CreateTime string // use for entity timestamps too
	User       string

	// Cache of entities this Tx is dealing with. Things can get funky if
	// we have more than one instance of the same entity in memory.
	// TODO DUG expand this to save all types, not just Versions.
	// Also, consider having Commit() just automatically call ValidateAndSave
	// for all entities in the Tx - then people don't need to call save
	// explicitly
	// Registries map[string]*Registry // reg.UID
	// Groups     map[string]*Group    // reg.DbSID+g.UID
	// Resources  map[string]*Resource // reg.DbSID+g.DbSID+r.UID
	Versions map[string]*Version // reg.DbSID+g.DbSID+r.DbSID+v.UID
	// contains filtered or unexported fields
}

Holds info about the current transaction. In a lot of ways this is similar to golang's Context in that it holds other info related to the current changes that are going on. Maybe one day convert this to a Context where Tx is just as apsect of it.

func NewTx

func NewTx() *Tx

func (*Tx) AddVersion

func (tx *Tx) AddVersion(v *Version)

func (*Tx) Commit

func (tx *Tx) Commit() error

func (*Tx) Conditional

func (tx *Tx) Conditional(err error) error

func (*Tx) GetVersion

func (tx *Tx) GetVersion(r *Resource, vID string) *Version

func (*Tx) NewTx

func (tx *Tx) NewTx()

It's ok for this to be called multiple times for the same Tx just to make sure we have an active transaction - it's a no-op at that point

func (*Tx) Prepare

func (tx *Tx) Prepare(query string) (*sql.Stmt, error)

func (*Tx) Rollback

func (tx *Tx) Rollback() error

func (*Tx) String

func (tx *Tx) String() string

type Version

type Version struct {
	Entity
	Resource *Resource
}

func (*Version) Delete

func (v *Version) Delete(nextVersionID string) error

func (*Version) Get

func (v *Version) Get(name string) any

func (*Version) JustSet

func (v *Version) JustSet(name string, val any) error

func (*Version) SetCommit

func (v *Version) SetCommit(name string, val any) error

func (*Version) SetDefault

func (v *Version) SetDefault() error

func (*Version) SetSave

func (v *Version) SetSave(name string, val any) error

Jump to

Keyboard shortcuts

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