gen

package
v0.1.21 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2024 License: GPL-2.0 Imports: 18 Imported by: 3

Documentation

Index

Constants

View Source
const (
	ParamContext      = "ctx"
	ParamID           = "id"
	ParamObject       = "obj"
	ParamVivardEngine = "vivard"
)
View Source
const (
	AnnotationDeletable = "deletable"
	// AnnotationAccess - log access (currently only createdOn and modifiedOn)
	AnnotationAccess = "access"

	CodeGeneratorOptionsName = "go"

	AnnotationBulk    = "bulk" // special annotation for bulk operations
	AnnotationBulkNew = "new"
	AnnotationBulkSet = "set"
)
View Source
const (
	FeatGoKind FeatureKind = "go"

	FCGSingletonAttrName = "engineAttr"

	// FCGType - jen.Code feature for *Entity and *Field;
	FCGType = "type"
	// FCGAttrType - jen.Code feature for *Field - type of attr in struct (maybe pointer);
	FCGAttrType = "attr-type"
	// FCGName - string; name of field or struct
	FCGName = "name"
	// FCGPointer - bool; true if attr is pointer in the struct
	FCGPointer = "is-pointer"
	// FCGBaseTypeAccessorName - name of function to access base type
	FCGBaseTypeAccessorName = "base-type-accessor"
	// FCGBaseTypeAccessorInterface - name of function to access base type
	FCGBaseTypeAccessorInterface = "base-type-interface"
	// FCGBaseTypeNameType - name of type for Type identifier
	FCGBaseTypeNameType = "base-type-type-name"
	// FCGDerivedTypeNameConst - name of constant for derived type
	FCGDerivedTypeNameConst = "derived-type-name"
	// FCGCalculated - field should not be stored; instead will be resolved on demand
	FCGCalculated = "calculated"
	// FCGScriptingRequired - feature for package - it is neccessary to create reference to scripting engine from package engine
	FCGScriptingRequired = "scripting-required"
	// FCGScriptingCreated - feature for package - it is neccessary to create reference to scripting engine from package engine
	FCGScriptingCreated = "scripting-created"
	// FCGExtEngineVar - for Field - name of engine var in engine for external types
	FCGExtEngineVar = "ext-engine-var"
	// FCGDeletable - the entity is deletable
	FCGDeletable = "deletable"
	// FCGLogCreated - createdOn field and its filling is required
	FCGLogCreated = "created"
	// FCGLogCreatedBy - createdBy field and its filling from context is required
	FCGLogCreatedBy = "created-by"
	// FCGLogModified - modifiedOn field and its filling is required
	FCGLogModified = "modified"
	// FCGLogModifiedBy - modifiedBy field and its filling is required
	FCGLogModifiedBy = "modified-by"
	// FCGDeletedFieldName - for entity; name of the deleted field (empty if not needed)
	FCGDeletedFieldName = "del-fld-name"
	// FCGDeletedField - for field; set to true for DeletedOn field
	FCGDeletedField = "del-fld"
	// FCGLogCreatedField - createdOn field
	FCGLogCreatedField = "created-fld"
	// FCGLogModifiedField - modifiedOn field
	FCGLogModifiedField = "modified-fld"
	// FCGLogCreatedByField - createdBy field
	FCGLogCreatedByField = "created-by"
	// FCGLogModifiedByField - modifiedBy field
	FCGLogModifiedByField = "modified-by"
	// FCGBulkNew - for Entity; true if should be generated bulk New operations
	FCGBulkNew = "bulk-new"
	// FCGBulkSet - for Entity; true if should be generated bulk Set operation
	FCGBulkSet = "bulk-set"
)
View Source
const (
	TipString = "string"
	TipInt    = "int"
	TipFloat  = "float"
	TipBool   = "bool"
	TipDate   = "date"
	TipAny    = "any"
	TipAuto   = "auto"

	EngineVar = "eng"

	ExtendableTypeDescriptorFieldName = "V_Type"
)
View Source
const (
	VivardPackage      = "github.com/vc2402/vivard"
	VivardPackageAlias = "vivard"
)
View Source
const (
	// AnnotationRefPackage creates reference to engine from given package as Engine's
	AnnotationRefPackage = "ref"
	// ARFPackageName name of package to include (may be just the nameless parameter of annotation)
	ARFPackageName = "name"
	// ARFPackageNames string of space delimited package names
	ARFPackageNames = "packages"

	// AnnotationEngineless tells not to generate Engine class for package
	AnnotationEngineless = "engineless"
)

File(package) scope annotations

View Source
const (
	//AnnotationFind may be used for defining Find params definition
	AnnotationFind = "find"

	//AnnFndFieldTag tag for find Field annotation - links input field to Entity field
	AnnFndFieldTag = "field"
	//AnnFndTypeTag tag for comparision type (see AFT*values)
	AnnFndTypeTag = "type"
	//AFFDeleted special value for field deleted
	AFFDeleted = "_deleted_"
	//AFTEqual - value for type find tag - equal to (default value)
	AFTEqual = "eq"
	//AFTNotEqual - value for type find tag - not equal to
	AFTNotEqual = "ne"
	// AFTGreaterThan - value for type find tag - greater than
	AFTGreaterThan = "gt"
	// AFTGreaterThanOrEqual - value for type find tag - greater than or equal to
	AFTGreaterThanOrEqual = "gte"
	// AFTLessThan - value for type find tag - less than
	AFTLessThan = "lt"
	// AFTLessThanOrEqual - value for type find tag - less than or equal to
	AFTLessThanOrEqual = "lte"
	// AFTStartsWith - like or regexp for start
	AFTStartsWith = "starts-with"
	// AFTContains - like or regexp for start
	AFTContains = "contains"
	// AFTStartsWithIgnoreCase - like or regexp for start
	AFTStartsWithIgnoreCase = "starts-with-ignore-case"
	// AFTContainsIgnoreCase - like or regexp for start
	AFTContainsIgnoreCase = "contains-ignore-case"
	// AFTIgnore - for deleted; if true - include deleted items
	AFTIgnore = "ignore"
	// AFTIsNull - null nullable fields (value should be bool)
	AFTIsNull    = "is-null"
	AFTIsNotNull = "is-not-null"
	// AFTExists - check weather value exists (value should be bool)
	AFTExists    = "exists"
	AFTNotExists = "not-exists"

	// AnnotationLookup for lookup function generation
	AnnotationLookup       = "lookup"
	ALEqual                = "eq"
	ALNotEqual             = "ne"
	ALStartsWith           = "startsWith"
	ALStartsWithIgnoreCase = "startsWithIgnoreCase"
	ALContains             = "contains"
	ALContainsIgnoreCase   = "containsIgnoreCase"

	// AnnotationCall - annotation for hook method
	AnnotationCall = "call"
	//AnnCallName - name of function to call
	AnnCallName = "name"
	//AnnCallJS - bool - name is JS script name
	AnnCallJS = "js"

	//AnnotationGo for common go-specific annotation
	AnnotationGo = "go"
	//AnnGoPackage defines package name for external type
	AnnGoPackage = "package"

	//AnnotationConfig for config members
	AnnotationConfig = "config"
	//AnnCfgValue shows that type describes cfg value
	AnnCfgValue = "value"
	//AnnCfgGroup shows that type describes cfg group
	AnnCfgGroup = "group"
	//AnnCfgMutable shows that this config field can be changed (generates save func for it)
	AnnCfgMutable = "mutable"

	//AnnotationDefault set default value for entity's field
	AnnotationDefault = "default"

	// AnnotationSort indicate to use this field for sorting (usually at db access moment)
	AnnotationSort = "sort"
	// AnnSortAscending sort in ascending order
	AnnSortAscending = "asc"
	// AnnSortDescending sort in descending order
	AnnSortDescending = "desc"

	// AnnotationReadonly may be used for fields that can not be changed via API calls
	AnnotationReadonly = "readonly"
)
View Source
const (
	// FeaturesCommonKind kind for common features
	FeaturesCommonKind FeatureKind = "gen"

	//FeaturesHookCodeKind - code for *Entity; creates hook code for hook's string (empty string or name with prefix);
	//    args: defaultNameOfFunction - string for function name if not set by modifier
	//          obj - object to call hook on
	//          newObj - new (old) value for object where applicable (nil if not)
	//          ctx - context object (string or jen.Code) (ctx by default)
	//	        eng - engine (eng by default)
	FeaturesHookCodeKind FeatureKind = "hook"

	//FCIgnore - bool; ignore common actions for this field/type
	FCIgnore = "ignore"
	// FCOneToManyField - *Field; common feature for description one to many field
	FCOneToManyField = "one-to-many-field"
	// FCOneToManyType - *Entity; common feature, reference to on to many type
	FCOneToManyType = "one-to-many-type"
	// FCForeignKey - *Entity; common feature for type showing that this type is many-to-one relation entity (value - type it references to)
	FCForeignKey = "foreign-key"
	// FCForeignKeyField - *Field; common feature for type, reference to its field that holds FK id
	FCForeignKeyField = "foreign-key-field"
	//FCModifiedFieldName - string; name for generated field storing value that field value was modified; should be requested via Descriptor
	FCModifiedFieldName = "modified-field-name"
	//FCViaParentAccessors - bool; generate accessors only via parent's object (for foreign-key types)
	FCViaParentAccessors = "access-via-parent"
	//FCComplexAccessor - bool; for field; if true - getter and setter for this field are complex (via eng)
	FCComplexAccessor = "complex-accessor"
	//FCSkipAccessors - bool, *Entity; do not generate setter and getter methods for Type
	FCSkipAccessors = "skip-accessors"
	//FCAttrIsPointer - bool; *Field; true if field for attr is pointer in the Go struct
	FCAttrIsPointer = "attr-is-pointer"
	//FCManyToManyType - type references to
	FCManyToManyType = "many-to-many-type"
	//FCManyToManyIDField - reference to id Field
	FCManyToManyIDField = "many-to-many-id"
	//FCRefsAsManyToMany - boolean for *Entity; true if there are refs to this entity as many to many field
	FCRefsAsManyToMany = "refs-many-to-many"
	//FCReadonly - boolean for *Entity(hardcodded) or *Field - the field is unmutable from api
	FCReadonly = "readonly"

	//FCObjIDCode returns code for *Entity: obj.Id(param if any may be string (var name) or jen.Code (var); by default - obj)
	FCObjIDCode = "id-accessor-code"
	//FCSetterCode returns code For *Field for setter(params if any are obj, value, context, defaults: obj, val, ctx)
	FCSetterCode = "setter-code"
	//FCGetterCode returns code for:
	//   *Field for getter(param if any are obj and context, defaults: obj, ctx);
	// or *Entity get object(params if any are objectID, ctx and engine, defaults: id, ctx, eng)
	//  first bool param is 'append ret with error' (by default true fo Entity)
	FCGetterCode = "getter-code"
	//FCIsNullCode returns code for IsAttrNull
	FCIsNullCode = "is-attr-null"
	//FCSetNullCode returns code for SetAttrNull
	FCSetNullCode = "set-attr-null"
	//FCAttrValueCode - code for access dereferenced attr value (returns code for e.g. *obj.attr); param (if any): obj
	FCAttrValueCode = "get-attr-code"
	//FCAttrSetCode - code to set dereferenced attr value  (returns code for e.g. *obj.attr = val); params (if any): obj, val
	FCAttrSetCode = "set-attr-code"
	//FCAttrIsEmptyCode - code for create bool value to check whether attr is empty  (returns code for e.g. obj.attr = nil); params (if any): obj
	//  if bool param found and it is true, returns nil if attr can't be empty
	FCAttrIsEmptyCode = "attr-is-empty-code"
	//FCListDictByIDCode - code for *Entity; list dictionary items by their ids; params: ids - array of ids, ctx
	FCListDictByIDCode = "fc-list-dict-by-id"
	//FCListByIDCode - code for *Entity; list items by their ids; params: ids - array of ids, ctx
	FCListByIDCode = "fc-list-by-id"
	//FCDictGetter - code for readonly dict getter (if any)
	FCDictGetter = "fc-dict-getter"
	//FCDictIniter - code for init dict values (if empty)
	FCDictIniter = "fc-dict-initer"
	//FCDictEnsurer - code for values that should be in the dict
	FCDictEnsurer = "fc-dict-ensurer"
	//FCEngineVar - code feature for Field - returns code for engine to access this field (usualy *Engine but checks package)
	FCEngineVar = "engine-var"
	//FCDescendants - array of *Entity that are descendants of this type
	FCDescendants = "descendants"
)
View Source
const (
	//FeaturesDBKind - common kind for db features
	FeaturesDBKind FeatureKind = "db"

	//FDBIncapsulate - bool; (for one-to-many field) store as array in document db
	FDBIncapsulate = "incapsulate"
	//FDBFlushDict - code for flushing whole dictionary to storage
	FDBFlushDict = "flush_dict"
)
View Source
const (

	//TypeHookCreate creates hook to call before new object creation; default name: "OnCreate"; can be set only for singleton
	TypeHookCreate = "create"
	//TypeHookChange creates hook to call before object change; default name: "OnChange";
	// params: ctx Context.context, eng *Engine, oldValue *Type, newValue *Type
	//  oldValue is nil for Create operation; newValue is nil for Delete operation
	//  should return error, if return not nil changes will not be saved
	TypeHookChange = "change"
	//TypeHookChanged creates hook to call after object was changed; default name: "OnSaved";
	// params: ctx Context.context, eng *Engine, oldValue *Type, newValue *Type
	//  oldValue is nil for Create operation; newValue is nil for Delete operation
	//  should return error, if return not nil changes will not be saved
	TypeHookChanged = "changed"
	//TypeHookStart creates hook to call on singleton after all the objects created; default name: "OnStart";
	TypeHookStart = "start"
	//TypeHookMethod is used for Methods calls
	TypeHookMethod = "method"
	//TypeHookTime allows to call method of singleton at specific time or periodically
	TypeHookTime = "time"
	//TypeHookDelete sets Entity's hook should be called before deleting an instance; default name OnDelete.
	//  Function should return error; if not nil object will not be deleted
	TypeHookDelete = "delete"

	//AttrHookSet - set may be used for complex fields (will be called before save)
	AttrHookSet = "set"
	//AttrHookCalculate - will be called when calculated field should be resolved (method of *Engine with params ctx and *object)
	AttrHookCalculate = "resolve"

	//MethodHookTime allows to call method of singleton at specific time or periodically
	MethodHookTime = "time"

	//HookJSPrefix - prefix for js script
	HookJSPrefix = "js"
	//HookGoPrefix - prefix for go function
	HookGoPrefix = "go"
	//WithoutEngSuffix - suffix of name string showing not to include engine param
	WithoutEngSuffix = "%eng"
)
View Source
const (
	//FeaturesAPIKind - common kind of api specific fetures and flags
	FeaturesAPIKind FeatureKind = "api"

	//FAPILevel - string; for *Entity; level of API generation
	FAPILevel = "level"
	//FAPILIgnore - value for FAPILevel: generate nothing
	FAPILIgnore = "ignore"
	//FAPILTypes - value for FAPILevel: generate types only
	FAPILTypes = "types"
	//FAPILAll - value for FAPILevel: generate everything
	FAPILAll = "all"

	//FAPIFindParam - *Entity; for *Entity; type for find method param
	FAPIFindParamType = "find-param-type"
	//FAPIFindFor - for *Entity or *Field - ref to object this is find for
	FAPIFindFor = "find-for"
	//FAPIFindForEmbedded - for *Field - array of fields (if find for attr of embedded type)
	FAPIFindForEmbedded = "find-for-emb"
	//FAPIFindForName - for *Field - name of type this is find for
	FAPIFindForName = "find-for-name"
	//FAPIFindParam - string; for *Field; find param descriptor (values as for @AnnFndTypeTag)
	FAPIFindParam = "find-param"
)
View Source
const (
	//FeatureChangeDetectorKind - kind of features related to detecting of fields changes
	FeaturesChangeDetectorKind FeatureKind = "changes"

	//FCDRequired for Field should be bool; for Entity - one of FCDREntity or FCDRField
	FCDRequired = "required"
	//FCDREntity - value for FCDRequired (for Entity) - detect changes for all the fields of Entity
	FCDREntity = "entity"
	// FCDRField - value for FCDRequired (for Entity) - detect changes only for selected fields (with FCDRequired = true)
	FCDRField = "field"
	//FCDChangedHook bool feature for Entity or Field - returns true if exists change hook generator and hook will be called (use via Project.GetFeature)
	FCDChangedHook = "changed-hook"
	//FCDChangedCode - code for *Field - generates bool expression, that returns true if field was changed (better approach is to use hook)
	FCDChangedCode = "changed"
)
View Source
const (

	// AnnQual - may be used for dictionary fields to show that it is depends on another dictionary
	// Field ma be ref to another dict or array to it; may be Nullable or no Null
	AnnQual = "qualifier"
	// AnnQualBy - annotation for field of type ref to dictionary, should contain id of field that is used as qualifier for qualified dictionairy
	AnnQualBy = "qualified-by"
	// AnnIndex forces to build index by field
	AnnIndex = "index"
)
View Source
const (
	//FeatureDictKind is used for dictionary features
	FeatureDictKind = "dict"

	//FDQualified - bool for Etnity - true if the dictionary has qualifier field
	FDQualified = "qualified"

	// FDQualifier - bool for Field or *Field for Entity
	//  for Field set if it is qualifier for this dict Entity
	//  for Entity refs to qualifier Field
	FDQualifier = "qualifier"

	// FDQualifierType - *Entity for Entity, refs to dictionary type that qualifier field refs to
	FDQualifierType = "qualifier-type"

	// FDQualifiedBy - *Field for Field, refs the field in the same Entity that is qualifier for this dict field
	FDQualifiedBy = "qual-by"

	// FDQualifiedByConst - *Field for Field, refs the field in the same Entity that is qualifier for this dict field
	FDQualifiedByConst = "qual-by-const"

	// FDQualifierFor - *Field for Field, refs to field requires this as qualifier
	FDQualifierFor = "qualifier-for"

	// FDCacheFieldName - string; field name in Engine for cache
	FDCacheFieldName = "cache-field"

	// FDIdxFieldName - string; field name in Engine for index
	FDIdxFieldName = "idx-field"

	// FDIndexes - array of indexDescriptor
	FDIndexes = "indexes"
)
View Source
const (
	DictCacheTempl          = "%sCache"
	DictIndexCacheTempl     = "%sCacheIndex"
	DictQualIndexCacheTempl = "%s%sCacheIndex"
	DictCacheLoaderTempl    = "%sEnsureCache"
	DictCacheMutexSuffix    = "Lock"
)
View Source
const (
	EngineVivard = "Vivard"

	InternalPackageName = "vivintrnl"
)
View Source
const (
	GQLAnnotation              = "gql"
	GQLAnnotationNameTag       = "name"
	GQLAnnotationSkipTag       = "skip"
	GQLAnnotationGetTag        = "get"
	GQLAnnotationSetTag        = "set"
	GQLAnnotationCreateTag     = "create"
	GQLAnnotationListTag       = "list"
	GQLAnnotationLookupTag     = "lookup"
	GQLAnnotationDeleteTag     = "delete"
	GQLAnnotationQueryTag      = "query"
	GQLAnnotationMutationTag   = "mutation"
	GQLAnnotationBulkCreateTag = "bulkCreate"
	GQLAnnotationBulkSetTag    = "bulkSet"
	// GQLAnnotationReadonlyTag do not generate GraphQL mutations for type
	GQLAnnotationReadonlyTag = "readonly"
)
View Source
const (
	GQLFeatures        = "gql"
	GQLFTypeTag        = "type"
	GQLFUseDefinedType = "use-defined-type"
	GQLFArgTypeTag     = "argType"
	GQLFIdTypeTag      = "idType"
	GQLFInputTypeName  = "inputType"
	GQLFMethodName     = "name"
	// GQLFMethodType - GQLFMethodTypeMutation or GQLFMethodTypeQuery
	GQLFMethodType         = "method-type"
	GQLFMethodTypeMutation = "mutation"
	GQLFMethodTypeQuery    = "query"
	// GQLFIDOnly use only id for embedded type
	GQLFIDOnly   = "id-only"
	GQLFReadonly = "redonly"

	// GQLFMethodResultType - code generator for method's result type
	GQLFMethodResultType = "result-type"
	// GQLFMethodResultTypeName - feature for method's result type name
	GQLFMethodResultTypeName = "result-type-name"
	// GQLGenerateUnionType - feature for Package; returns function that generates union type
	//  and inserts generator in given Package's init procedure
	//  function gets union name as first param and types (*Entity) that should be parts of union
	GQLGenerateUnionType = "generate-union-type"
	// GQLFSetNullInputField name of boolean field in input type for setting null for nullbale field
	GQLFSetNullInputField = "set-null-input-field"
)
View Source
const (
	FeatureHistKind FeatureKind = "historic"

	// FHCollect - boolean for field: history collection is required
	FHCollect = "collect"

	//FHHistoryFieldName - string: name of historic attr in object
	FHHistoryFieldName = "hist-field-name"

	//FHHistoryField - string: name of historic attr in object
	FHHistoryField = "hist-field"

	//FHHistoryEntityName - string: name of entity for history
	FHHistoryEntityName = "hist-entity-name"

	//FHHistoryEntity - *Entity: entity for history
	FHHistoryEntity = "hist-entity"

	//FHHistoryOf - *Field - for field refs field it holds history of; for entity - entity for which field this entity is created
	FHHistoryOf = "history-of"

	FHKind       = "kind"
	FHkField     = "field"
	FHkTimestamp = "timestamp"
	FHkUserID    = "uid"
	FHkUserName  = "username"
	FHkSource    = "source"
	FHkCustom    = "custom"

	FHAttr = "attr"

	FHType      = "type"
	FHtSetter   = "setter"
	FHtFunction = "function"
)
View Source
const (
	//well known var names
	//GHVObject default name of object (this) var
	GHVObject = "obj"
	//GHVContext default name of context var
	GHVContext = "ctx"
	//GHVEngine default name of engine var
	GHVEngine = "eng"
)
View Source
const (
	VariantZap    = "zap"
	VariantLogrus = "logrus"
)
View Source
const (
	LogFeatureKind FeatureKind = "logger-feature"

	// LFWarn returns code for warn (params: message and pairs key/value)
	LFWarn = "warn"
	// LFDebug returns code for debug (params: message and pairs key/value)
	LFDebug = "debug"
	// LFError returns code for error (params: message and pairs key/value)
	LFError = "error"

	OptionLoggerGenerator = "logger-generator"
	OptionsVariant        = "variant"
)
View Source
const (
	CFGPointEnterBeforeHooks = "enter-before-hooks"
	CFGPointEnterAfterHooks  = "enter-after-hooks"
	CFGPointMainAction       = "main-action"
	CFGPointExitBeforeHooks  = "exit-before-hooks"
	CFGPointExitAfterHooks   = "exit-after-hooks"
	CFGPointExitError        = "exit-error"
)

points for CodeFragmentProvider

View Source
const (
	CFGEngineEnter         = "engine-enter"
	CFGEngineExit          = "engine-exit"
	CFGEngineMembers       = "engine-members"
	CFGEngineFileGlobals   = "engine-globals"
	CFGEngineFileFunctions = "engine-functions"
)

points for CodeFragmentProvider

View Source
const (
	ResourceFeatureKind FeatureKind = "resource-feature"
	// RFKKey may be set tor Entity that is resource or Package to define its resource key
	RFKKey         = "key"
	RFKParent      = "parent"
	RFKCheckAccess = "check-access"
	RFConstName    = "const"
	RFVarName      = "var"
	// RFResources is map of required resources for package
	RFResources = "resources"
	// RFRequired set to true for package if there are resources
	RFRequired           = "required"
	RFManagerField       = "manager-field"
	RFAccessCheckerField = "access-checker"
)
View Source
const (
	SequenceFeatures FeatureKind = "seq-id"

	SFSetCurrentValue = "set-current-value"
	// SFGenerateSequenceCall code feature returns function tah generates code for getting next value from sequence
	//  function params: sequenceName string, receiver jen.Code
	SFGenerateSequenceCall = "seq-call"
)
View Source
const (
	ServiceFeatureKind FeatureKind = "service-feature"
	// SFKProvide is used for Singleton's field if inject required
	SFKProvide = "provide"
	// SFKInject is used for Singleton if at least one field of it requires SFKProvide
	SFKInject = "inject"
	// SFKRegister is used for singleton if it is required to register it as service
	SFKRegister = "register"
	// SFKEngineService requests Engine ref to service; returns field's name; params: serviceName, serviceAlias and, optionally, type and package
	SFKEngineService = "engine-service"
)
View Source
const (
	SQLPackage  = "github.com/vc2402/vivard/sql"
	SQLXPackage = "github.com/vc2402/vivard/sqlx"
)
View Source
const (
	ValidatorGeneratorName = "Validator"
	FeaturesValidator      = "validator"

	FVValidateFunc       = "validate-func"
	FVValidationRequired = "required"
)
View Source
const (
	VersionFeatureKind FeatureKind = "f-ver"
	// VFField if set for Entity version should be tracked in field with name as feature value
	VFField = "field"
	// VFBehaviour is string (one of  vaBehaviourWarning, vaBehaviourError or vaBehaviourNothing)
	//  means what to do if version of saving object is not the same as current
	VFBehaviour    = "beh"
	VFTryMerge     = "mer"
	VFScope        = "scope"
	VFSequenceName = "seq-name"

	VersionDefaultFieldName = "Version"
)
View Source
const GQLGeneratorName = "GraphQL"
View Source
const (
	ResourcePackage = "github.com/vc2402/vivard/resource"
)
View Source
const ValidatorFuncNameTemplate = "Validate%s"
View Source
const ValidatorOptionsName = "validatorGO"

Variables

View Source
var (
	//CodeFragmentModuleGeneral module of general functionality
	CodeFragmentModuleGeneral = &struct{}{}
)
View Source
var MethodsNamesTemplates = [methodMax]string{
	"Get%s",
	"Set%s",
	"New%s",
	"Delete%s",
	"Generate%sID",
	"GetAll%s",
	"Init%s",
	"New%ss",
	"Set%ss",
	"Load%s",
	"Save%s",
	"Update%s",
	"Create%s",
	"Remove%s",
	"RemoveFK%s",
	"ReplaceFK%s",
	"Lookup%s",
	"List%s",
	"ListFK%s",
	"Find%s",
	"Is%sChanged",
}

MethodsNamesTemplates contains templates for standart methods names

Functions

func AnyToReflect

func AnyToReflect(opt any, to reflect.Value) error

func FindFieldInStruct

func FindFieldInStruct(struc reflect.Type, name string) (int, bool)

func IsPrimitiveType

func IsPrimitiveType(name string) bool

func OptionsAnyToStruct

func OptionsAnyToStruct(opts any, to any) (err error)

func RegisterPlugin

func RegisterPlugin(plugin Generator)

func ToSnakeCase

func ToSnakeCase(str string) string

ToSnakeCase - thanks to stower (https://gist.github.com/stoewer/fbe273b711e6a06315d19552dd4d33e6)

Types

type Annotation

type Annotation struct {
	Pos  lexer.Position
	Name string `@AnnotationTag `
	// Spec   string           //`( ":" @Ident )?`
	Values []*AnnotationTag `("(" (@@)* ")")?`
}

func (*Annotation) Append

func (a *Annotation) Append(another *Annotation)

Add adds values from another to a rewrites values with the same key

func (*Annotation) GetBool

func (a *Annotation) GetBool(key string, def bool) (ret bool)

func (*Annotation) GetBoolTag

func (a *Annotation) GetBoolTag(key string) (ret bool, ok bool)

func (*Annotation) GetFloat

func (a *Annotation) GetFloat(key string, def float64) (ret float64)

func (*Annotation) GetFloatTag

func (a *Annotation) GetFloatTag(key string) (ret float64, ok bool)

func (*Annotation) GetInt

func (a *Annotation) GetInt(key string, def int) (ret int)

func (*Annotation) GetIntTag

func (a *Annotation) GetIntTag(key string) (ret int, ok bool)

func (*Annotation) GetInterfaceTag

func (a *Annotation) GetInterfaceTag(key string) (ret interface{}, ok bool)

func (*Annotation) GetNameTag

func (a *Annotation) GetNameTag(key string) (ret string, ok bool)

func (*Annotation) GetString

func (a *Annotation) GetString(key string, def string) (ret string)

func (*Annotation) GetStringTag

func (a *Annotation) GetStringTag(key string) (ret string, ok bool)

func (*Annotation) GetTag

func (a *Annotation) GetTag(key string) *AnnotationTag

func (*Annotation) SetTag

func (a *Annotation) SetTag(key string, val interface{})

type AnnotationTag

type AnnotationTag struct {
	Pos   lexer.Position
	Key   string           `(@Ident | @String)`
	Value *AnnotationValue `( "=" @@ )?`
}

func (*AnnotationTag) GetBool

func (at *AnnotationTag) GetBool() (ret bool, ok bool)

func (*AnnotationTag) GetFloat

func (at *AnnotationTag) GetFloat() (ret float64, ok bool)

func (*AnnotationTag) GetInt

func (at *AnnotationTag) GetInt() (ret int, ok bool)

func (*AnnotationTag) GetString

func (at *AnnotationTag) GetString() (ret string, ok bool)

type AnnotationValue

type AnnotationValue struct {
	String    *string  ` ( @String `
	Bool      *Boolean `| @("true" | "false") `
	Number    *float64 `| @Number | @Int)`
	Interface interface{}
}

type Annotations

type Annotations map[string]*Annotation

func (Annotations) AddTag

func (a Annotations) AddTag(name string, key string, val interface{}, spec ...string) error

func (Annotations) Append

func (a Annotations) Append(another Annotations)

Append appends all annotation from another to a

func (Annotations) ByPrefix

func (a Annotations) ByPrefix(prefix string, includeUnspec bool) map[string]*Annotation

ByPrefix returns Annotations of kind prefix:name with given prefix; keys are names only params: prefix - first part of name includeUnspec - include annotation without specifier (with name == kind)

func (Annotations) Find

func (a Annotations) Find(name, spec string) *Annotation

Find returns Annotation of kind prefix:name if any; nil otherwise

func (Annotations) GetBoolAnnotation

func (a Annotations) GetBoolAnnotation(name string, key string) (val bool, ok bool)

func (Annotations) GetBoolAnnotationDef

func (a Annotations) GetBoolAnnotationDef(name string, key string, def bool) bool

func (Annotations) GetInterfaceAnnotation

func (a Annotations) GetInterfaceAnnotation(name string, key string) (val interface{})

func (Annotations) GetNameAnnotation

func (a Annotations) GetNameAnnotation(name string, key string) (val string, ok bool)

GetNameAnnotation returns string tag annotation with given name if any or first tag key if it is bool and true

e.g. in case $ann(someValue) it returns 'someValue' and for $ann(someValue name="somName") returns someName

func (Annotations) GetStringAnnotation

func (a Annotations) GetStringAnnotation(name string, key string) (val string, ok bool)

GetStringAnnotation returns string annotation with given name if any; ok is false otherwise

func (Annotations) GetStringAnnotationDef

func (a Annotations) GetStringAnnotationDef(name string, key string, def string) (val string)

func (Annotations) GetStringAnnotationDefTrimmed

func (a Annotations) GetStringAnnotationDefTrimmed(name string, key string, def string) (val string)

type AttrModifier

type AttrModifier string
const (
	AttrModifierEmbedded    AttrModifier = "embedded"
	AttrModifierEmbeddedRef AttrModifier = "ref-embedded"
	AttrModifierID          AttrModifier = "id"
	AttrModifierIDAuto      AttrModifier = "auto"
	AttrModifierForeignKey  AttrModifier = "foreign-key"
	AttrModifierOneToMany   AttrModifier = "one-to-many"
	AttrModifierCalculated  AttrModifier = "calculated"
	AttrModifierAuxiliary   AttrModifier = "auxiliary"
)

type AutoGenerateIDFieldBehaviour

type AutoGenerateIDFieldBehaviour bool
const (
	AutoGenerateIDField      AutoGenerateIDFieldBehaviour = true
	DoNotAutoGenerateIDField AutoGenerateIDFieldBehaviour = false
)

type BitSetChangeDetectorGenerator

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

BitSetChangeDetectorGenerator generates code for historic fields or whole entities (recording changes)

func (*BitSetChangeDetectorGenerator) CheckAnnotation

func (cdg *BitSetChangeDetectorGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

CheckAnnotation checks that annotation may be utilized by CodeGeneration

func (*BitSetChangeDetectorGenerator) Generate

func (cdg *BitSetChangeDetectorGenerator) Generate(b *Builder) (err error)

Generate from generator interface

func (*BitSetChangeDetectorGenerator) Name

func (*BitSetChangeDetectorGenerator) OnEntityHook

func (cdg *BitSetChangeDetectorGenerator) OnEntityHook(name HookType, mod HookModifier, e *Entity, vars *GeneratorHookVars) (code *jen.Statement, order int)

OnEntityHook implements GeneratorHookHolder

func (*BitSetChangeDetectorGenerator) OnFieldHook

func (cdg *BitSetChangeDetectorGenerator) OnFieldHook(name HookType, mod HookModifier, f *Field, vars *GeneratorHookVars) (code *jen.Statement, order int)

OnFieldHook implements GeneratorHookHolder

func (*BitSetChangeDetectorGenerator) OnMethodHook

func (cdg *BitSetChangeDetectorGenerator) OnMethodHook(name HookType, mod HookModifier, m *Method, vars *GeneratorHookVars) (code *jen.Statement, order int)

OnMethodHook implements GeneratorHookHolder

func (*BitSetChangeDetectorGenerator) Prepare

func (cdg *BitSetChangeDetectorGenerator) Prepare(desc *Package) error

Prepare from Generator interface

func (*BitSetChangeDetectorGenerator) ProvideFeature

func (cdg *BitSetChangeDetectorGenerator) ProvideFeature(kind FeatureKind, name string, obj interface{}) (feature interface{}, ok ProvideFeatureResult)

ProvideFeature from FeatureProvider interface

func (*BitSetChangeDetectorGenerator) SetDescriptor

func (cdg *BitSetChangeDetectorGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

type Boolean

type Boolean bool

func (*Boolean) Capture

func (b *Boolean) Capture(values []string) error

type Builder

type Builder struct {
	*Project
	Descriptor *Package
	*File
	JenFile *jen.File
	Types   *jen.Statement

	Functions *jen.Statement
	Generator *jen.Statement
	// contains filtered or unexported fields
}

func (*Builder) AddConst

func (b *Builder) AddConst(section string, stmt *jen.Statement)

AddConst adds statement to const section (const word will be added automatically); it may be few named const sections, each will be organized as const() block

func (*Builder) AddGlobal

func (b *Builder) AddGlobal(section string, stmt *jen.Statement)

AddGlobal adds statement to var section (var word will be added autimatically); it may be few named var sections, each will be organized as var() block

func (*Builder) GetComplexMethodName

func (b *Builder) GetComplexMethodName(t *Entity, f *Field, method CSComplexMethodKind) string

func (*Builder) GetMethodName

func (b *Builder) GetMethodName(f *Field, method CSMethodKind) string

func (*Builder) GoType

func (b *Builder) GoType(ref *TypeRef, embedded ...bool) *jen.Statement

GoType returns statement with Go type for ref

type CSComplexMethodKind

type CSComplexMethodKind int
const (
	CGGetComplexAttrMethod CSComplexMethodKind = iota
	CGSetComplexAttrMethod
	CGAddComplexAttrMethod
)

type CSMethodKind

type CSMethodKind int
const (
	CGSetterMethod CSMethodKind = iota
	CGGetterMethod
	CGIsNullMethod
	CGSetNullMethod
	CGIsChangedMethod
)

type ClientOutputDirOption

type ClientOutputDirOption string

type CodeFragmentContext

type CodeFragmentContext struct {
	MethodName string
	TypeName   string
	MethodKind
	//EngineAvailable true if eng var does exist in scope
	EngineAvailable bool
	//ErrVar holds err var name or empty if err not defined yet
	ErrVar string
	//ObjVar holds name of object var
	ObjVar string
	//Builder reference to Builder
	*Builder
	//Package refers to Package object if it is Package context (e.g. Engine fragments)
	*Package
	//Entity holds reference to Entity definition if it is entity-level function
	Entity *Entity
	//Field holds reference to Field if it is Field-level function
	Field *Field
	//Params holds function params by well-known names
	Params map[string]string
	//ErrorRet should be set to correct code generated by AddCheckError method; if empty return statement will be also empty
	ErrorRet []jen.Code
	//BeforeReturnError can be set to add process before error return statement
	BeforeReturnError func()
	// contains filtered or unexported fields
}

CodeFragmentContext holds context of function

func (*CodeFragmentContext) Add

func (cf *CodeFragmentContext) Add(code ...jen.Code) *jen.Statement

func (*CodeFragmentContext) AddCheckError

func (cf *CodeFragmentContext) AddCheckError()

func (*CodeFragmentContext) AddOnErrorReturnStatement

func (cf *CodeFragmentContext) AddOnErrorReturnStatement()

func (*CodeFragmentContext) Enter

func (cf *CodeFragmentContext) Enter(beforeHooks bool)

func (*CodeFragmentContext) Exit

func (cf *CodeFragmentContext) Exit(beforeHooks bool)

func (*CodeFragmentContext) GetErr

func (cf *CodeFragmentContext) GetErr() *jen.Statement

func (*CodeFragmentContext) GetErrName

func (cf *CodeFragmentContext) GetErrName() string

func (*CodeFragmentContext) GetObjVar

func (cf *CodeFragmentContext) GetObjVar() *jen.Statement

func (*CodeFragmentContext) GetObjVarName

func (cf *CodeFragmentContext) GetObjVarName() string

func (*CodeFragmentContext) GetParam

func (cf *CodeFragmentContext) GetParam(name string) *jen.Statement

func (*CodeFragmentContext) GetParamName

func (cf *CodeFragmentContext) GetParamName(name string) string

func (*CodeFragmentContext) MainAction

func (cf *CodeFragmentContext) MainAction() bool

func (*CodeFragmentContext) MustProject

func (cf *CodeFragmentContext) MustProject() *Project

func (*CodeFragmentContext) Pop

func (cf *CodeFragmentContext) Pop()

func (*CodeFragmentContext) Project

func (cf *CodeFragmentContext) Project() *Project

func (*CodeFragmentContext) Push

func (cf *CodeFragmentContext) Push(g *jen.Group)

type CodeFragmentProvider

type CodeFragmentProvider interface {
	//ProvideCodeFragment should return code fragment for given point
	// module is high-level generation abstraction (e.g., go skeleton or db)
	// action is more low-level (like setter) and depends on module
	// point is place inside action (e.g. function-enter)
	// ctx contains context like params, variables names etc.
	// for go it should be *CodeFragmentContext instance and code should be added via this object;
	//  return value of nil in this case shows that nothing was added;
	ProvideCodeFragment(module interface{}, action interface{}, point interface{}, ctx interface{}) interface{}
}

CodeFragmentProvider provides fragment of code

type CodeGenerator

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

CodeGenerator generates Go code (structs, methods, Engine object and other)

func (*CodeGenerator) CheckAnnotation

func (cg *CodeGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

CheckAnnotation checks that annotation may be utilized by CodeGeneration

func (*CodeGenerator) Generate

func (cg *CodeGenerator) Generate(bldr *Builder) (err error)

Generate from generator interface

func (*CodeGenerator) Name

func (cg *CodeGenerator) Name() string

Name returns name of Generator

func (*CodeGenerator) Prepare

func (cg *CodeGenerator) Prepare(desc *Package) error

Prepare from Generator interface

func (*CodeGenerator) ProcessMeta

func (cg *CodeGenerator) ProcessMeta(desc *Package, m *Meta) (bool, error)

ProcessMeta - implement MetaProcessor

func (*CodeGenerator) ProvideCodeFragment

func (cg *CodeGenerator) ProvideCodeFragment(
	module interface{},
	action interface{},
	point interface{},
	ctx interface{},
) interface{}

func (*CodeGenerator) ProvideFeature

func (cg *CodeGenerator) ProvideFeature(
	kind FeatureKind,
	name string,
	obj interface{},
) (feature interface{}, ok ProvideFeatureResult)

ProvideFeature from FeatureProvider interface

func (*CodeGenerator) SetDescriptor

func (cg *CodeGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

type CodeGeneratorOptions

type CodeGeneratorOptions struct {
	// GenerateFieldsAccessors - generate Get and Set for each field (returns non pointers for basic types)
	GenerateFieldsAccessors bool
	// GenerateNullMethods - generate IsNull and SetNull methods for each nullable field
	GenerateNullMethods bool
	// GenerateFieldsEnums - generate int consts for each field of each type, e.g. 'Type1Field1Field' (maybe used for NullableField, search filters etc.)
	GenerateFieldsEnums bool
	// GenerateRemoveOperation - generate Remove and Delete operations for each entity
	GenerateRemoveOperation bool
	// GenerateDeletedField - generate field DeletedOn *time.Time for every entity that can be deleted
	GenerateDeletedField bool
	// GenerateAccessField - generate fields CreatedOn and ModifiedOn (time.Time) for entities
	GenerateAccessField EntityTypeSelector
	// GenerateCreatedBy - generate field CreatedBy by default (only if corresponding access field is generated)
	GenerateCreatedBy bool
	// GenerateModifiedBy - generate fields ModifiedBy by default (only if corresponding access field is generated)
	GenerateModifiedBy bool
	// AllowEmbeddedArraysForDictionary - allow arrays of embedded types for dictionary
	AllowEmbeddedArraysForDictionary bool
	// GenerateBulkNew - generate bulk new operations for every type (default false)
	GenerateBulkNew bool
	// GenerateBulkSet - generate bulk set operations for every type (default false)
	GenerateBulkSet bool
}

CodeGeneratorOptions describes possible options for CodeGenerator

type CodeHelperFunc

type CodeHelperFunc func(args ...interface{}) jen.Code

CodeHelperFunc Feature type for helping generate code (params depends on feature)

type CroneGenerator

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

CroneGenerator generates Go code for @time hook

func (*CroneGenerator) CheckAnnotation

func (cg *CroneGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

CheckAnnotation checks that annotation may be utilized by CodeGeneration

func (*CroneGenerator) Generate

func (cg *CroneGenerator) Generate(bldr *Builder) (err error)

Generate from generator interface

func (*CroneGenerator) Name

func (cg *CroneGenerator) Name() string

func (*CroneGenerator) Prepare

func (cg *CroneGenerator) Prepare(desc *Package) error

Prepare from Generator interface

type DefaultPackageOption

type DefaultPackageOption string

type DefinedType

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

func (*DefinedType) Entity

func (dt *DefinedType) Entity() *Entity

Entity returns underlying type

func (*DefinedType) Enum added in v0.1.7

func (dt *DefinedType) Enum() *Enum

Enum returns underlying type

func (*DefinedType) IdType added in v0.1.7

func (dt *DefinedType) IdType() (string, error)

func (*DefinedType) Position added in v0.1.7

func (dt *DefinedType) Position() lexer.Position

type DescriptorAware

type DescriptorAware interface {
	//SetDescriptor will be called for all objects before first call of Generator methods
	SetDescriptor(proj *Project)
}

DescriptorAware may be used in case if generator requires reference to descriptor object

type DictionariesGenerator

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

func (*DictionariesGenerator) CheckAnnotation

func (ncg *DictionariesGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*DictionariesGenerator) Generate

func (ncg *DictionariesGenerator) Generate(b *Builder) (err error)

func (*DictionariesGenerator) Name

func (ncg *DictionariesGenerator) Name() string

func (*DictionariesGenerator) Prepare

func (ncg *DictionariesGenerator) Prepare(desc *Package) error

func (*DictionariesGenerator) ProvideCodeFragment

func (ncg *DictionariesGenerator) ProvideCodeFragment(
	module interface{},
	action interface{},
	point interface{},
	ctx interface{},
) interface{}

func (*DictionariesGenerator) ProvideFeature

func (ncg *DictionariesGenerator) ProvideFeature(
	kind FeatureKind,
	name string,
	obj interface{},
) (feature interface{}, ok ProvideFeatureResult)

ProvideFeature from FeatureProvider interface

func (*DictionariesGenerator) SetDescriptor

func (ncg *DictionariesGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

type EngineDescriptor

type EngineDescriptor struct {
	Fields         *jen.Statement
	Initializator  *jen.Statement
	SingletonInits map[string]*jen.Statement
	Initialized    *jen.Statement
	Start          *jen.Statement
	Functions      *jen.Statement
	// contains filtered or unexported fields
}

type Entity

type Entity struct {
	Pos          lexer.Position
	Modifiers    []*EntityModifier `( (@@)* )? `
	Name         string            `"type" (@Ident | @QualifiedName)  `
	BaseTypeName string            `( "extends" (@Ident | @QualifiedName) )? "{"`
	Entries      []*Entry          `( @@ )*`
	Incomplete   bool              `(@More)? "}"`
	Fields       []*Field
	Methods      []*Method
	FieldsIndex  map[string]*Field
	MethodsIndex map[string]*Method
	Annotations  Annotations
	// Features - generators created values based on Annotations, generators options...
	Features     Features
	TypeModifers map[TypeModifier]bool
	// BaseType      *Entity
	Pckg *Package
	// BaseFieldTags map[string]string
	BaseField       *Field
	File            *File
	FullAnnotations Annotations
}

func (*Entity) AddDescendant

func (e *Entity) AddDescendant(desc *Entity)

func (*Entity) AddField

func (e *Entity) AddField(name string, tip string) (*Field, error)

func (*Entity) FB

func (e *Entity) FB(kind FeatureKind, name string) bool

FB shorcut to Features.String()

func (*Entity) FS

func (e *Entity) FS(kind FeatureKind, name string) string

FS shorcut to Features.String()

func (*Entity) GetAnnotation

func (e *Entity) GetAnnotation(name string, spec ...string) *Annotation

GetAnnotation looks for annotation in FullAnnotations (including BaseType annotations)

func (*Entity) GetBaseField

func (e *Entity) GetBaseField() *Field

func (*Entity) GetBaseType

func (e *Entity) GetBaseType() *Entity

func (*Entity) GetField

func (e *Entity) GetField(name string) *Field

func (*Entity) GetFields

func (e *Entity) GetFields(includeBase bool, baseInline bool) []*Field

func (*Entity) GetFullAnnotations

func (e *Entity) GetFullAnnotations() Annotations

GetFullAnnotations returns annotation including base type annotations

func (*Entity) GetIdField

func (e *Entity) GetIdField() *Field

func (*Entity) GetMethodName

func (e *Entity) GetMethodName(mk MethodKind) string

GetMethodName returns name for method of given kind

func (*Entity) GetName

func (e *Entity) GetName() string

GetName returns name of entity

func (*Entity) HasModifier

func (e *Entity) HasModifier(mod TypeModifier) bool

func (*Entity) HaveHook

func (e *Entity) HaveHook(key string) (val *Hook, ok bool)

func (*Entity) IsDictionary

func (e *Entity) IsDictionary() bool

func (*Entity) IsNameQualified

func (e *Entity) IsNameQualified() bool

func (*Entity) Package

func (e *Entity) Package() string

func (*Entity) TypeRef

func (e *Entity) TypeRef() *TypeRef

type EntityModifier

type EntityModifier struct {
	Pos          lexer.Position
	Hook         *Hook             `( @@`
	Annotation   *Annotation       `| @@`
	TypeModifier *TypeModifierType `| @@ )`
}

type EntityTypeSelector

type EntityTypeSelector string
const (
	EntityTypeAll           EntityTypeSelector = "all"
	EntityTypeNone          EntityTypeSelector = "none"
	EntityTypeNonDictionary EntityTypeSelector = "non-dictionary"
)

type Entry

type Entry struct {
	Pos       lexer.Position
	Field     *Field           `( @@  `
	Method    *Method          `|  @@ )`
	Modifiers []*EntryModifier `( "<" ( @@ )* ">")? ";"`
}

type EntryModifier

type EntryModifier struct {
	Pos          lexer.Position
	Hook         *Hook       `( @@`
	AttrModifier string      `| @AttrModifier`
	Annotation   *Annotation `| @@ )`
}

type Enum added in v0.1.7

type Enum struct {
	Pos          lexer.Position
	Modifiers    []*EntityModifier `( (@@)* )? `
	Name         string            `"enum" @Ident "{"`
	Fields       []*EnumField      `( @@ )* "}"`
	Pckg         *Package
	File         *File
	AliasForType string
	Features     Features
}

func (*Enum) GetDefaultValue added in v0.1.7

func (e *Enum) GetDefaultValue(forPackage *Package) *jen.Statement

type EnumField added in v0.1.7

type EnumField struct {
	Pos       lexer.Position
	Name      string   ` @Ident ( "=" `
	IntVal    *int     ` ( @Int `
	FloatVal  *float64 ` | @Number `
	StringVal *string  ` | @String ) )? ";" `
	Parent    *Enum
}

type ExtendableTypeDescriptorBehaviour

type ExtendableTypeDescriptorBehaviour int
const (
	GenerateStringFieldForExtendableTypes ExtendableTypeDescriptorBehaviour = iota
	GenerateIntFieldForExtendableTypes
	DoNotGenerateFieldForExtendableTypes
)

type FeatureArguments

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

type FeatureFunc

type FeatureFunc func(args ...interface{}) (any, error)

FeatureFunc may be returned by feature provider

type FeatureKind

type FeatureKind string

type FeatureProvider

type FeatureProvider interface {
	//ProvideFeature - returns feature result and ok if can provided requested feature; nil and false otherwise
	// params: kind and name of feature,
	// obj - whether *Entity, *Field or *Method
	ProvideFeature(kind FeatureKind, name string, obj interface{}) (feature interface{}, ok ProvideFeatureResult)
}

FeatureProvider provides features for code generation

type Features

type Features map[string]interface{}

func (Features) Bool

func (f Features) Bool(kind FeatureKind, name string) (val bool)

Bool looks for feature and asserts it to bool if any; otherwise return false

func (Features) Get

func (f Features) Get(kind FeatureKind, name string) (val interface{}, ok bool)

Get looks for feature and returns it if any

func (Features) GetBool

func (f Features) GetBool(kind FeatureKind, name string) (val bool, ok bool)

GetBool looks for feature and asserts it to bool if any

func (Features) GetEntity

func (f Features) GetEntity(kind FeatureKind, name string) (val *Entity, ok bool)

GetEntity looks for feature and asserts it to *Entity if any

func (Features) GetField

func (f Features) GetField(kind FeatureKind, name string) (val *Field, ok bool)

GetField looks for feature and asserts it to *Field if any

func (Features) GetString

func (f Features) GetString(kind FeatureKind, name string) (val string, ok bool)

GetString looks for feature and asserts it to string if any

func (Features) Name

func (f Features) Name(kind FeatureKind, name string) string

Name returns string representing given kind and name

func (Features) Set

func (f Features) Set(kind FeatureKind, name string, feat interface{})

Set adds feature to a feature set

func (Features) Stmt

func (f Features) Stmt(kind FeatureKind, name string) (val *jen.Statement)

Stmt looks for feature and asserts it to *jen.Statement if any; otherwise returns empty statement

func (Features) String

func (f Features) String(kind FeatureKind, name string) (val string)

String looks for feature and asserts it to string if any; otherwise returns empty string

type Field

type Field struct {
	Pos         lexer.Position
	Modifiers   []*EntryModifier
	Name        string   `@Ident ":"`
	Type        *TypeRef `@@`
	Tags        map[string]string
	Annotations Annotations
	// Features - generators created values based on Annotations, generators options...
	Features Features
	// contains filtered or unexported fields
}

func (*Field) FB

func (f *Field) FB(kind FeatureKind, name string) bool

FB shorcut to Features.String()

func (*Field) FS

func (f *Field) FS(kind FeatureKind, name string) string

FS shorcut to Features.String()

func (*Field) HasModifier

func (f *Field) HasModifier(mod AttrModifier) bool

func (*Field) HaveHook

func (f *Field) HaveHook(key string) (val *Hook, ok bool)

func (*Field) IsIdField

func (f *Field) IsIdField() bool

func (*Field) Parent

func (f *Field) Parent() *Entity

Parent returns enclosing entity

func (*Field) PostProcess

func (f *Field) PostProcess()

type File

type File struct {
	Pos         lexer.Position
	Name        string
	FileName    string
	Modifiers   []*PackageModifier `( (@@)*`
	Package     string             `"package" @Ident ";")?`
	Meta        []*Meta            `( @@ `
	Entries     []*Entity          `| @@ `
	Enums       []*Enum            `| @@ )*`
	Pckg        *Package
	Annotations Annotations
}

func Parse

func Parse(files []string) ([]*File, error)

func (*File) AddEntity

func (f *File) AddEntity(e *Entity)

type GQLGenerator

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

func (*GQLGenerator) CheckAnnotation

func (cg *GQLGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*GQLGenerator) Generate

func (cg *GQLGenerator) Generate(b *Builder) (err error)

func (*GQLGenerator) GetGQLEntityTypeName

func (cg *GQLGenerator) GetGQLEntityTypeName(name string) (ret string)

func (*GQLGenerator) GetGQLFieldName

func (cg *GQLGenerator) GetGQLFieldName(f *Field) string

func (*GQLGenerator) GetGQLInputTypeName

func (cg *GQLGenerator) GetGQLInputTypeName(name string) (ret string)

func (*GQLGenerator) GetGQLMethodName

func (cg *GQLGenerator) GetGQLMethodName(e *Entity, m *Method) string

func (*GQLGenerator) GetGQLOperationName

func (cg *GQLGenerator) GetGQLOperationName(e *Entity, tip GQLOperationKind) string

func (*GQLGenerator) GetGQLTypeName

func (cg *GQLGenerator) GetGQLTypeName(ref *TypeRef, forInput ...bool) (ret string)

func (*GQLGenerator) GetInputGoType

func (cg *GQLGenerator) GetInputGoType(ref *TypeRef) *jen.Statement

func (*GQLGenerator) Name

func (cg *GQLGenerator) Name() string

func (*GQLGenerator) Prepare

func (cg *GQLGenerator) Prepare(desc *Package) error

func (*GQLGenerator) ProvideFeature

func (cg *GQLGenerator) ProvideFeature(
	kind FeatureKind,
	name string,
	obj interface{},
) (feature interface{}, ok ProvideFeatureResult)

ProvideFeature from FeatureProvider interface

type GQLOperationKind

type GQLOperationKind int
const (
	GQLOperationGet GQLOperationKind = iota
	GQLOperationSet
	GQLOperationCreate
	GQLOperationList
	GQLOperationLookup
	GQLOperationDelete
	GQLOperationFind
	GQLOperationBulkCreate
	GQLOperationBulkSet

	GQLOperationLast
)

type GQLOptions

type GQLOptions struct {
	UsePackageNameInTypeNames bool
}

type GenerationStage

type GenerationStage int
const (
	StageParsing GenerationStage = iota
	StageBeforePrepare
	StagePrepare
	StageMetaProcessing
	StageGenerating
)

type Generator

type Generator interface {
	// Name returns the unique name of generator (plugin)
	Name() string
	// CheckAnnotation calls for every annotation to check that it is understandable
	// item contains whether *Entity, *Field or *Method
	// return (true, nil) if Generator does understand this annotation
	//        (false, nil) if Generator does not understand this annotation
	// error should be returned if annotation is understandable but contains errors
	CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)
	// Prepare - prepare to generation
	Prepare(desc *Package) error
	// Generate - do generate
	Generate(bldr *Builder) error
}

Generator interface can be used for creating custom generators

type GeneratorHookHolder

type GeneratorHookHolder interface {
	//OnEntityHook may be called for Entity for given hook name
	//  if returned value is not nil, it will be added to code in consideration to order
	//  vars contains var names for common objects (ctx, eng, obj); may be nil, in this case defaults will be used
	OnEntityHook(name HookType, mod HookModifier, e *Entity, vars *GeneratorHookVars) (code *jen.Statement, order int)

	//OnFieldHook may be called for Field for given hook name
	//  if returned value is not nil, it will be added to code in consideration to order
	//  vars contains var names for common objects (ctx, eng, obj); may be nil, in this case defaults will be used
	OnFieldHook(name HookType, mod HookModifier, f *Field, vars *GeneratorHookVars) (code *jen.Statement, order int)

	//OnMethodHook may be called for Method for given hook name
	//  if returned value is not nil, it will be added to code in consideration to order
	//  vars contains var names for common objects (ctx, eng, obj); may be nil, in this case defaults will be used
	OnMethodHook(name HookType, mod HookModifier, m *Method, vars *GeneratorHookVars) (code *jen.Statement, order int)
}

GeneratorHookHolder - interface for hooks code generation

type GeneratorHookVars

type GeneratorHookVars struct {
	// Ctx - variable name or context *jen.Statement if it is not "ctx"; if ctx is not available should be false
	Ctx interface{}
	// Eng - variable name or Engine *jen.Statement if it is not "eng"; if there is no Engine in context should be false
	Eng interface{}
	// Obj - variable name or object *jen.Statement if it is not "obj"
	Obj interface{}
	//Others - additional well known for some hooks vars with their names (there are no defaults for others - all should be set as var name or statement)
	Others map[string]interface{}
}

GeneratorHookVars holds available variables for generator hooks

func NewHookVars

func NewHookVars(vars ...interface{}) *GeneratorHookVars

NewHookVars creates new instance of *GeneratorHookVars with vars given as args

each var is a pair of name and value(string or *jen.Statement)
names may be well known names

func (*GeneratorHookVars) GetCtx

func (ha *GeneratorHookVars) GetCtx() *jen.Statement

GetCtx returns statement for context var; returns nil it is unavailabe

func (*GeneratorHookVars) GetEngine

func (ha *GeneratorHookVars) GetEngine() *jen.Statement

GetEngine returns statement for engine var; returns nil it is unavailabe

func (*GeneratorHookVars) GetObject

func (ha *GeneratorHookVars) GetObject() *jen.Statement

GetObject returns statement for object (this) var; returns nil it is unavailabe

func (*GeneratorHookVars) GetVar

func (ha *GeneratorHookVars) GetVar(name string) *jen.Statement

GetObject returns statement for object (this) var; returns nil it is unavailabe

func (*GeneratorHookVars) MustCtx

func (ha *GeneratorHookVars) MustCtx() *jen.Statement

MustCtx returns statement for context var; panics if it is unavailable

func (*GeneratorHookVars) MustEngine

func (ha *GeneratorHookVars) MustEngine() *jen.Statement

MustEngine returns statement for engine var; panics if it is unavailable

func (*GeneratorHookVars) MustObject

func (ha *GeneratorHookVars) MustObject() *jen.Statement

MustEngine returns statement for engine var; panics if it is unavailable

type HistoryGenerator

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

HistoryGenerator generates code for historic fields or whole entities (recording changes)

func (*HistoryGenerator) CheckAnnotation

func (hg *HistoryGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

CheckAnnotation checks that annotation may be utilized by CodeGeneration

func (*HistoryGenerator) Generate

func (hg *HistoryGenerator) Generate(b *Builder) (err error)

Generate from generator interface

func (*HistoryGenerator) Name

func (hg *HistoryGenerator) Name() string

func (*HistoryGenerator) OnEntityHook

func (hg *HistoryGenerator) OnEntityHook(name HookType, mod HookModifier, e *Entity, vars *GeneratorHookVars) (code *jen.Statement, order int)

OnEntityHook implements GeneratorHookHolder

func (*HistoryGenerator) OnFieldHook

func (hg *HistoryGenerator) OnFieldHook(name HookType, mod HookModifier, f *Field, vars *GeneratorHookVars) (code *jen.Statement, order int)

OnFieldHook implements GeneratorHookHolder

func (*HistoryGenerator) OnMethodHook

func (hg *HistoryGenerator) OnMethodHook(name HookType, mod HookModifier, m *Method, vars *GeneratorHookVars) (code *jen.Statement, order int)

OnMethodHook implements GeneratorHookHolder

func (*HistoryGenerator) Prepare

func (hg *HistoryGenerator) Prepare(desc *Package) error

Prepare from Generator interface

func (*HistoryGenerator) SetDescriptor

func (hg *HistoryGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

type Hook

type Hook struct {
	Key   string `@HookTag`
	Spec  string `( ":" @Ident )?`
	Value string `("=" @String)?`
}

type HookArgParam

type HookArgParam struct {
	Name  string
	Param interface{}
}

type HookArgsDescriptor

type HookArgsDescriptor struct {
	// Str  - string arg (defaultName for Go hooks)
	Str string
	// Ctx - variable name or context *jen.Statement if it is not "ctx"
	Ctx interface{}
	// Eng - variable name or Engine *jen.Statement if it is not "eng"; false to force not add engine arg
	Eng interface{}
	// Obj - variable name or object *jen.Statement if it is not "obj"
	Obj interface{}
	//Params - additional params with their names
	Params []HookArgParam
	//ErrVar - assign error return value to variable
	ErrVar interface{}
}

HookArgsDescriptor holds args for feature hook function

type HookFeatureFunc

type HookFeatureFunc func(args HookArgsDescriptor) jen.Code

HookFeatureFunc func can be returned as feature that can create code for hook

type HookModifier

type HookModifier string
const (
	//HMStart - start of function
	HMStart HookModifier = "start"
	//HMExit - last statements of function
	HMExit HookModifier = "exit"
	//HMError - error in function
	HMError HookModifier = "error"
	//HMModified - field was modified (just before save)
	HMModified HookModifier = "modified"
)

type HookType

type HookType string
const (
	//HookSet will be called on Set for field (start, exit, error)
	HookSet HookType = "gen:Set"
	//HookSetNull will be called on Set for field (start, exit, error)
	HookSetNull HookType = "gen:SetNull"
	//HookGet will be called on Get for field (start, exit, error)
	HookGet HookType = "gen:Get"
	//HookNew will be called on New for entity (start, exit, error)
	HookNew HookType = "gen:New"
	//HookDelete will be called on Delete for entity (start, exit, error)
	HookDelete HookType = "gen:Del"
	//HookLoad will be called on Load for entity (start, exit, error)
	HookLoad HookType = "gen:Load"
	//HookSave will be called on Save for entity (start, exit, error) and for field (modified)
	HookSave HookType = "gen:Save"
	//HookUpdate will be called on Update for entity (start, exit, error) and for field (modified)
	HookUpdate HookType = "gen:Update"
	//HookSave will be called on Create for entity (start, exit, error) and for field (modified)
	HookCreate HookType = "gen:Create"
)

standart hooks

type LoggerGenerator

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

func (*LoggerGenerator) CheckAnnotation

func (cg *LoggerGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*LoggerGenerator) Generate

func (cg *LoggerGenerator) Generate(b *Builder) (err error)

func (*LoggerGenerator) Name

func (cg *LoggerGenerator) Name() string

func (*LoggerGenerator) Prepare

func (cg *LoggerGenerator) Prepare(desc *Package) error

func (*LoggerGenerator) ProvideFeature

func (cg *LoggerGenerator) ProvideFeature(kind FeatureKind, name string, obj interface{}) (feature interface{}, ok ProvideFeatureResult)

func (*LoggerGenerator) SetDescriptor

func (cg *LoggerGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

func (*LoggerGenerator) SetOptions

func (cg *LoggerGenerator) SetOptions(options any) error

type MapType

type MapType struct {
	KeyType   string   `"map" "[" (@"int"|@"string") "]"`
	ValueType *TypeRef `@@`
}

type Meta

type Meta struct {
	Pos      lexer.Position
	TypeName string   ` "meta" ( "(" @Ident ")" )?`
	Lines    []string ` (@MetaLine)* `

	TypeRef *Entity
	// contains filtered or unexported fields
}

func (*Meta) Current

func (m *Meta) Current() []string

Current returns current slice of meta lines (delimited by empty lines)

func (*Meta) Err

func (m *Meta) Err() error

Err returns current error state

func (*Meta) Next

func (m *Meta) Next() bool

Next looks for next slice; returns true if any false if no more slices found

func (*Meta) Position

func (m *Meta) Position() lexer.Position

Position returns position with lines offset

type MetaProcessor

type MetaProcessor interface {
	//ProcessMeta should try to process current slice in given meta and return true on success;
	//  error shows that there are problems in known format
	ProcessMeta(desc *Package, m *Meta) (bool, error)
}

MetaProcessor meta processor interface

type Method

type Method struct {
	Pos         lexer.Position
	Modifiers   []*EntryModifier
	Name        string         `@Ident "("`
	Params      []*MethodParam ` (  (@@) ("," @@)* )? `
	RetValue    *TypeRef       `")" (":" @@)?`
	Annotations Annotations
	// Features - generators created values based on Annotations, generators options...
	Features Features
	// contains filtered or unexported fields
}

func (*Method) FB

func (m *Method) FB(kind FeatureKind, name string) bool

FB shorcut to Features.String()

func (*Method) FS

func (m *Method) FS(kind FeatureKind, name string) string

FS shorcut to Features.String()

func (*Method) HaveHook

func (m *Method) HaveHook(key string) (val *Hook, ok bool)

func (*Method) Parent

func (m *Method) Parent() *Entity

Parent returns enclosing entity

type MethodKind

type MethodKind int

MethodKind type of generated method

const (

	//MethodGet for Getter for type
	MethodGet MethodKind = iota
	//MethodSet is setter
	MethodSet
	//MethodNew is creator of new instance (gets already filled struct as argument)
	MethodNew
	//MethodDelete deletes instance
	MethodDelete
	//MethodGenerateID returnes id for new entity
	MethodGenerateID
	//MethodGetAll may be used for types with small amount of instances (dictionaries, etc)
	MethodGetAll
	//MethodInit inits new struct (if necessary fills id with auto value)
	MethodInit
	// MethodNewBulk creates set of new instances
	MethodNewBulk
	// MethodSetBulk creates set of new instances
	MethodSetBulk

	//MethodLoad loads entity from a store
	MethodLoad
	//MethodSave saves existing entity into the store (replace entity with modified one)
	MethodSave
	//MethodUpdate updates existing entity into the store (only modified fields if available)
	MethodUpdate
	//MethodCreate creates (inserts) new entity
	MethodCreate
	//MethodRemove removes (or marks as deleted) entity
	MethodRemove
	//MethodRemoveFK removes entities for given parent key
	MethodRemoveFK
	//MethodReplaceFK removes entities for given parent key and inserts new (params: id and array of entities)
	MethodReplaceFK
	//MethodLookup returns items for given query
	MethodLookup
	//MethodList returns all items (for dictionaries)
	MethodList
	//MethodListFK returns all items (for one-to-many fields)
	MethodListFK
	//MethodFind can be used for looking for objects by some parameters
	MethodFind
	//MethodChanged returns true if attr was changed
	MethodChanged

	EngineNotAMethod
	MethodEnginePrepare
	MethodEngineStart
	MethodEngineRegisterService
	TypeFieldNotAMethod
)

type MethodParam

type MethodParam struct {
	Pos      lexer.Position
	Name     string   `@Ident ":"`
	Type     *TypeRef `@@`
	Features Features
}

type MongoGenerator

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

func (*MongoGenerator) CheckAnnotation

func (cg *MongoGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*MongoGenerator) Generate

func (cg *MongoGenerator) Generate(bldr *Builder) (err error)

func (*MongoGenerator) Name

func (cg *MongoGenerator) Name() string

func (*MongoGenerator) Prepare

func (cg *MongoGenerator) Prepare(desc *Package) error

func (*MongoGenerator) ProvideFeature

func (cg *MongoGenerator) ProvideFeature(
	kind FeatureKind,
	name string,
	obj interface{},
) (feature interface{}, ok ProvideFeatureResult)

ProvideFeature from FeatureProvider interface

func (*MongoGenerator) SetOptions

func (cg *MongoGenerator) SetOptions(options any) error

type NoCacheGenerator

type NoCacheGenerator struct {
	Options NoCacheOptions
	// contains filtered or unexported fields
}

func (*NoCacheGenerator) CheckAnnotation

func (ncg *NoCacheGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*NoCacheGenerator) Generate

func (ncg *NoCacheGenerator) Generate(b *Builder) (err error)

func (*NoCacheGenerator) Name

func (ncg *NoCacheGenerator) Name() string

func (*NoCacheGenerator) Prepare

func (ncg *NoCacheGenerator) Prepare(desc *Package) error

func (*NoCacheGenerator) ProvideFeature

func (ncg *NoCacheGenerator) ProvideFeature(
	kind FeatureKind,
	name string,
	obj interface{},
) (feature interface{}, ok ProvideFeatureResult)

ProvideFeature from FeatureProvider interface

type NoCacheOptions

type NoCacheOptions struct {
	GenerateForDictionaries bool
}

type NullsHandlingKind

type NullsHandlingKind int
const (
	// NullablePointers - all nullable fields will be pointers
	NullablePointers NullsHandlingKind = iota
	// NullableField - create special field for nulls handling
	NullableField
	// NullableStorableField - like NullableField but when storing in DB just store it (not convert null values to nulls in DB)
	NullableStorableField
	// NullableNothing - do nothing special for null handling (fields are not pointers, nulls - empty values) - default value
	NullableNothing
)

type ObjectRefGenerator

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

ObjectRefGenerator generates Go code for $object-ref annotations

func (*ObjectRefGenerator) CheckAnnotation

func (cg *ObjectRefGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

CheckAnnotation checks that annotation may be utilized by CodeGeneration

func (*ObjectRefGenerator) Generate

func (cg *ObjectRefGenerator) Generate(bldr *Builder) (err error)

Generate from generator interface

func (*ObjectRefGenerator) Name

func (cg *ObjectRefGenerator) Name() string

func (*ObjectRefGenerator) Prepare

func (cg *ObjectRefGenerator) Prepare(desc *Package) error

Prepare from Generator interface

func (*ObjectRefGenerator) SetDescriptor

func (cg *ObjectRefGenerator) SetDescriptor(proj *Project)

type OptionsSetter

type OptionsSetter interface {
	// SetOptions sets plugin specific options
	SetOptions(options any) error
}

OptionsSetter may be implemented by Generator if it depends on options

type Opts

type Opts struct {
	NullsHandling       NullsHandlingKind
	UnknownAnnotation   UnknownAnnotationBehaviour
	AutoGenerateIDField AutoGenerateIDFieldBehaviour
	DefaultPackage      string
	OutputDir           string
	ClientOutputDir     string
	PackagePrefix       string
	ExtendableTypeDescr ExtendableTypeDescriptorBehaviour

	Custom map[string]interface{}
}

func Options

func Options(opts ...interface{}) *Opts

Options creates new Opts object and initializes it with given values first three values, if strings, are OutputDir, DefaultPackage and ClientOutputDir (may be omitted)

PackagePrefix can be set with using corresponding type (DefaultPackageOption)

func (*Opts) CustomToStruct

func (o *Opts) CustomToStruct(name string, to interface{}) (found bool, err error)

func (*Opts) FromAny

func (o *Opts) FromAny(options any) error

func (*Opts) SetAutoGenerateIDField

func (o *Opts) SetAutoGenerateIDField(set AutoGenerateIDFieldBehaviour) *Opts

func (*Opts) SetClientOutputDir

func (o *Opts) SetClientOutputDir(cd string) *Opts

SetClientOutputDir sets default package for generator

func (*Opts) SetDefaultPackage

func (o *Opts) SetDefaultPackage(dp string) *Opts

SetDefaultPackage sets default package for generator

func (*Opts) SetOutputDir

func (o *Opts) SetOutputDir(od string) *Opts

SetOutputDir sets output dir for generator

func (*Opts) With

func (o *Opts) With(opts ...interface{}) *Opts

With add options to object

func (*Opts) WithCustom

func (o *Opts) WithCustom(name string, op interface{}) *Opts

type OutputDirectoryOption

type OutputDirectoryOption string

type Package

type Package struct {
	Name  string
	Files []*File

	Engine *EngineDescriptor
	*Project
	Features Features
	// contains filtered or unexported fields
}

Package - descriptor for generating package

func (*Package) AddBaseFieldTag

func (desc *Package) AddBaseFieldTag(e *Entity, key string, value string)

AddBaseFieldTag adds tag to Go struct

func (*Package) AddTag

func (desc *Package) AddTag(f *Field, key string, value string)

AddTag adds tag to Go struct

func (*Package) AddToEnginePrepare

func (desc *Package) AddToEnginePrepare(stmt *jen.Statement)

func (*Package) AddToEngineStart

func (desc *Package) AddToEngineStart(stmt *jen.Statement)

func (*Package) AddType

func (desc *Package) AddType(name string) (*Entity, error)

func (*Package) FindFieldsForComplexName

func (desc *Package) FindFieldsForComplexName(e *Entity, name string) ([]*Field, error)

func (*Package) FindType

func (desc *Package) FindType(name string) (dt *DefinedType, ok bool)

FindType looks for type descriptor and returns it

func (*Package) FindTypes

func (desc *Package) FindTypes(cb func(*Entity) bool) (ret []*Entity)

func (*Package) GetExtEngineRef

func (desc *Package) GetExtEngineRef(pckgName string) string

GetExtEngineRef returns name of property in Engine for external engine with name pckgName

func (*Package) GetFieldTypePackage

func (desc *Package) GetFieldTypePackage(f *Field) string

func (*Package) GetHookName

func (desc *Package) GetHookName(hookKind string, f *Field) string

GetHookName returns name for method of given kind

func (*Package) GetMethodName

func (desc *Package) GetMethodName(mk MethodKind, name string) string

GetMethodName returns name for method of given kind

func (*Package) GetRealTypeName

func (desc *Package) GetRealTypeName(tip string) string

func (*Package) GetTypeEngineAccessor

func (desc *Package) GetTypeEngineAccessor(t *Entity) jen.Code

func (*Package) GetTypePackage

func (desc *Package) GetTypePackage(tip string) string

func (*Package) GetTypePackageAlias

func (desc *Package) GetTypePackageAlias(tip string) string

func (*Package) GetTypeRefPackage

func (desc *Package) GetTypeRefPackage(tr *TypeRef) string

func (*Package) HasModifier

func (desc *Package) HasModifier(tr *TypeRef, modifier TypeModifier) bool

HasModifier checks whether type that given TypeRef refers to has modifier

func (*Package) Options

func (desc *Package) Options() *Opts

func (*Package) ParseAnnotationMeta

func (desc *Package) ParseAnnotationMeta(m *Meta) (ok bool, err error)

ParseAnnotationMeta tries to parse meta as annotations set

func (*Package) RegisterType

func (desc *Package) RegisterType(e *Entity)

RegisterType looks for type descriptor and returns it

func (*Package) TypeStmt

func (desc *Package) TypeStmt(e *Entity) *jen.Statement

type PackageModifier added in v0.1.7

type PackageModifier struct {
	Pos        lexer.Position
	Hook       *Hook       `( @@`
	Annotation *Annotation `| @@ )`
}

type PackagePrefixOption

type PackagePrefixOption string

type Project

type Project struct {
	Options  *Opts
	Files    []*File
	Warnings []string
	Errors   []error
	// contains filtered or unexported fields
}

func New

func New(files []*File, o *Opts) *Project

New creates new Project object

func (*Project) AddError

func (p *Project) AddError(err error)

func (*Project) AddWarning

func (p *Project) AddWarning(warn string)

func (*Project) CallCodeFeatureFunc

func (p *Project) CallCodeFeatureFunc(obj interface{}, kind FeatureKind, name string, args ...interface{}) jen.Code

CallCodeFeatureFunc looks for feature with given params, tries to assert it to CodeHelperFunc and call; panics if feature not found

func (*Project) CallFeatureFunc

func (p *Project) CallFeatureFunc(obj interface{}, kind FeatureKind, name string, args ...interface{}) (any, error)

CallFeatureFunc looks for feature with given params, tries to assert it to FeatureFunc and call and returns it's result; panics if feature not found

func (*Project) CallFeatureHookFunc

func (p *Project) CallFeatureHookFunc(obj interface{}, kind FeatureKind, name string, args HookArgsDescriptor) jen.Code

CallFeatureHookFunc looks for feature with given params, tries to assert it to HookFeatureFunc and call

func (*Project) CurrentStage

func (p *Project) CurrentStage() GenerationStage

CurrentStage returns current stage

func (*Project) FindType

func (p *Project) FindType(name string) (t *DefinedType, ok bool)

func (*Project) Generate

func (p *Project) Generate() (err error)

func (*Project) GetFeature

func (p *Project) GetFeature(obj interface{}, kind FeatureKind, name string) interface{}

GetFeature looks for feature in obj (*Package (for *Package and *Builder), *Entity, *Field or *Method); returns nil if feature not found

func (*Project) GetFeatureMust

func (p *Project) GetFeatureMust(obj interface{}, kind FeatureKind, name string) interface{}

GetFeatureMust looks for feature in obj (*Entity, *Field or *Method); panics if feature not found

func (*Project) GetFullPackage

func (p *Project) GetFullPackage(alias string) string

func (*Project) GetInternalPackage

func (p *Project) GetInternalPackage() *Package

func (*Project) GetPackage

func (p *Project) GetPackage(name string) *Package

func (*Project) GetTypePackage

func (p *Project) GetTypePackage(t *DefinedType) string

func (*Project) HasErrors

func (p *Project) HasErrors() bool

func (*Project) OnHook

func (p *Project) OnHook(name HookType, mod HookModifier, item interface{}, vars *GeneratorHookVars) (st *jen.Statement)

OnHook may be called during generation to add hooks code for item (may be *Field, *Method, *Entity)

vars contains var names for common objects (ctx, eng, obj); may be nil, in this case defaults will be used

func (*Project) Print

func (p *Project) Print()

func (*Project) ProvideCodeFragment

func (p *Project) ProvideCodeFragment(module interface{}, action interface{}, point interface{}, ctx interface{}, theOnly bool) interface{}

func (*Project) RegisterExternalType

func (p *Project) RegisterExternalType(pckg, alias string, name string) error

RegisterExternalType registers reference to external type

func (*Project) With

func (p *Project) With(gen Generator) *Project

With registers Generator gen

func (*Project) WithHookHolder

func (p *Project) WithHookHolder(hh GeneratorHookHolder) *Project

WithHookHolder registers HookHolder (registered Generator will be added automatically if it implements HookHolder interface)

func (*Project) WithMetaProcessor

func (p *Project) WithMetaProcessor(mp MetaProcessor) *Project

WithMetaProcessor registers meta processor (registered Generator will be added automatically if it implements MetaProcessor interface)

func (*Project) WithPlugin

func (p *Project) WithPlugin(name string, options interface{}) error

WithPlugin adds registered plugin as generator

func (*Project) WithPluginMust

func (p *Project) WithPluginMust(name string, options interface{}) *Project

WithPluginMust adds registered plugin as generator; panics in case of error

func (*Project) WriteToFiles

func (p *Project) WriteToFiles() (err error)

type ProvideFeatureResult

type ProvideFeatureResult int

ProvideFeatureResult special type for ProvideFeature return value

const (
	// FeatureNotProvided - provider can not provide this feature
	FeatureNotProvided ProvideFeatureResult = iota
	// FeatureProvided - feature result present feature that can be cached
	FeatureProvided
	// FeatureProvidedNonCacheable - feature result present feature that can not be cached
	FeatureProvidedNonCacheable
)

type ResourceGenerator

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

func (*ResourceGenerator) CheckAnnotation

func (cg *ResourceGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*ResourceGenerator) Generate

func (cg *ResourceGenerator) Generate(b *Builder) (err error)

func (*ResourceGenerator) Name

func (cg *ResourceGenerator) Name() string

func (*ResourceGenerator) Prepare

func (cg *ResourceGenerator) Prepare(desc *Package) error

func (*ResourceGenerator) ProvideCodeFragment

func (cg *ResourceGenerator) ProvideCodeFragment(module interface{}, action interface{}, point interface{}, ctx interface{}) interface{}

func (*ResourceGenerator) ProvideFeature

func (cg *ResourceGenerator) ProvideFeature(kind FeatureKind, name string, obj interface{}) (feature interface{}, ok ProvideFeatureResult)

func (*ResourceGenerator) SetDescriptor

func (cg *ResourceGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

func (*ResourceGenerator) SetOptions

func (cg *ResourceGenerator) SetOptions(options any) error

type SequnceIDGenerator

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

func (*SequnceIDGenerator) CheckAnnotation

func (cg *SequnceIDGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*SequnceIDGenerator) Generate

func (cg *SequnceIDGenerator) Generate(bldr *Builder) (err error)

func (*SequnceIDGenerator) Name

func (cg *SequnceIDGenerator) Name() string

func (*SequnceIDGenerator) Prepare

func (cg *SequnceIDGenerator) Prepare(desc *Package) error

func (*SequnceIDGenerator) ProvideFeature

func (cg *SequnceIDGenerator) ProvideFeature(kind FeatureKind, name string, obj interface{}) (feature interface{}, ok ProvideFeatureResult)

ProvideFeature from FeatureProvider interface

type ServiceGenerator

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

func (*ServiceGenerator) CheckAnnotation

func (cg *ServiceGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*ServiceGenerator) Generate

func (cg *ServiceGenerator) Generate(b *Builder) (err error)

func (*ServiceGenerator) Name

func (cg *ServiceGenerator) Name() string

func (*ServiceGenerator) Prepare

func (cg *ServiceGenerator) Prepare(desc *Package) error

func (*ServiceGenerator) ProvideCodeFragment

func (cg *ServiceGenerator) ProvideCodeFragment(module interface{}, action interface{}, point interface{}, ctx interface{}) interface{}

func (*ServiceGenerator) ProvideFeature

func (cg *ServiceGenerator) ProvideFeature(kind FeatureKind, name string, obj interface{}) (feature interface{}, ok ProvideFeatureResult)

func (*ServiceGenerator) SetDescriptor

func (cg *ServiceGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

type TypeModifier

type TypeModifier string
const (
	TypeModifierAbstract   TypeModifier = "abstract"
	TypeModifierConfig     TypeModifier = "config"
	TypeModifierDictionary TypeModifier = "dictionary"
	TypeModifierEmbeddable TypeModifier = "embeddable"
	TypeModifierExtendable TypeModifier = "extendable"
	TypeModifierExternal   TypeModifier = "extern"
	TypeModifierSingleton  TypeModifier = "singleton"
	TypeModifierTransient  TypeModifier = "transient"
)

type TypeModifierType

type TypeModifierType struct {
	Modifier TypeModifier `@( "abstract" | "config" | "dictionary" | "transient" | "embeddable" | "singleton" | "extern" | "extendable" )`
}

type TypeRef

type TypeRef struct {
	Array       *TypeRef `( "[" @@ "]"`
	Map         *MapType ` |  @@ `
	Ref         bool     ` | ( @"*" )?`
	Type        string   ` (@Ident | @QualifiedName | @"auto" ) )`
	NonNullable bool     `[ @"!" ]`
	Complex     bool
	Embedded    bool
}

type UnknownAnnotationBehaviour

type UnknownAnnotationBehaviour int
const (
	//UnknownAnnotationError - stop generation if unknown annotation is met
	UnknownAnnotationError UnknownAnnotationBehaviour = iota
	//UnknownAnnotationWarning - inform about unknown annotation and continue
	UnknownAnnotationWarning
	//UnknownAnnotationIgnore - ignore unknown annotation
	UnknownAnnotationIgnore
)

type Validator

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

func (*Validator) CheckAnnotation

func (cg *Validator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*Validator) Generate

func (cg *Validator) Generate(b *Builder) (err error)

func (*Validator) Name

func (cg *Validator) Name() string

func (*Validator) Prepare

func (cg *Validator) Prepare(desc *Package) error

func (*Validator) ProvideCodeFragment

func (cg *Validator) ProvideCodeFragment(module interface{}, action interface{}, point interface{}, ctx interface{}) interface{}

func (*Validator) SetDescriptor

func (cg *Validator) SetDescriptor(proj *Project)

func (*Validator) SetOptions

func (cg *Validator) SetOptions(opts any) error

type ValidatorOptions

type ValidatorOptions struct {
	// ValidateDictionaries defines behaviour of checking existing dictionary's value on instance create/set
	ValidateDictionaries bool `json:"validate_dictionaries"`
}

type VersionGenerator

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

func (*VersionGenerator) CheckAnnotation

func (cg *VersionGenerator) CheckAnnotation(desc *Package, ann *Annotation, item interface{}) (bool, error)

func (*VersionGenerator) Generate

func (cg *VersionGenerator) Generate(b *Builder) (err error)

func (*VersionGenerator) Name

func (cg *VersionGenerator) Name() string

func (*VersionGenerator) Prepare

func (cg *VersionGenerator) Prepare(desc *Package) error

func (*VersionGenerator) ProvideCodeFragment

func (ncg *VersionGenerator) ProvideCodeFragment(module interface{}, action interface{}, point interface{}, ctx interface{}) interface{}

func (*VersionGenerator) SetDescriptor

func (cg *VersionGenerator) SetDescriptor(proj *Project)

SetDescriptor from DescriptorAware

func (*VersionGenerator) SetOptions

func (cg *VersionGenerator) SetOptions(options any) error

type VersionOptions

type VersionOptions struct {
	// DefaultBehaviour behaviour on save with different version; default is warn (log file)
	// vaBehaviourWarning (warn), vaBehaviourError (err) or vaBehaviourNothing (ignore)
	DefaultBehaviour string
	// TryMerge try check whether changes are intersecting or no (requires changes recording)
	TryMerge         bool
	DefaultFieldName string
	// Scope whether object or type
	Scope string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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