geen

package
v5.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2021 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	YES yesOrNo = "Y"
	NO  yesOrNo = "N"
)

for Y / N questions

View Source
const (
	EntityFieldID           = "ID"
	EntityFieldKIND         = "Kind"
	EntityFieldENTITYSTATUS = "EntityStatus"
	EntityFieldCREATEDBYID  = "CreatedByID"
	EntityFieldCREATEDBY    = "CreatedBy"
	EntityFieldCREATION     = "Creation"
	EntityFieldDELETEDBYID  = "DeletedByID"
	EntityFieldDELETEDBY    = "DeletedBy"
	EntityFieldDELETION     = "Deletion"
	EntityFieldLABEL        = "Label"
	EntityFieldMODIFIEDBYID = "ModifiedByID"
	EntityFieldMODIFIEDBY   = "ModifiedBy"
	EntityFieldMODIFICATION = "Modification"
	EntityFieldLOADEDLINKS  = "LoadedLinks"
	EntityFieldKEY          = "Key"
	EntityFieldLOADINGID    = "LoadingID"
	EntityFieldHASH         = "Hash"
)

Constants for the names of some generic entity fields

View Source
const (
	BatchFunctionGEENBULKINSERTS c.BatchFuncName = "bulkInsertEntities"
)

Variables

View Source
var (
	TypeAMOUNT          = reflect.TypeOf((core.Amount)(0))
	TypeDURATION        = reflect.TypeOf((time.Duration)(0))
	TypeEMAIL           = reflect.TypeOf((core.Email)(""))
	TypeENTITY          = reflect.TypeOf((*Entity)(nil)).Elem()
	TypeENTITYID        = reflect.TypeOf((EntityID)(0))
	TypeENTITYREFERENCE = reflect.TypeOf((EntityReference)(""))
	TypeIACTIONTYPE     = reflect.TypeOf((*IActionType)(nil)).Elem()
	TypeIENTITY         = reflect.TypeOf((*IEntity)(nil)).Elem()
	TypeIENUM           = reflect.TypeOf((*IEnum)(nil)).Elem()
	TypeINT             = reflect.TypeOf((int)(0))
	TypeINT64           = reflect.TypeOf((int64)(0))
	TypeIUSER           = reflect.TypeOf((*IUser)(nil)).Elem()
	TypeRESOURCE        = reflect.TypeOf((*Resource)(nil)).Elem()
	TypeTIME            = reflect.TypeOf((*time.Time)(nil))
	TypeURL             = reflect.TypeOf((core.URL)(""))
	TypeWEBOPERATION    = reflect.TypeOf((*WebOperation)(nil)).Elem()
	TypeJSONString      = reflect.TypeOf((core.JSONString)(""))
)

Some variables containing types to help us referring to them

View Source
var (

	// OperandLESSTHAN : used to specify that a target entity property should be less than a given value
	OperandLESSTHAN = NewOperand("%s <= ?", "<=")
	// OperandMORETHAN : used to specify that a target entity property should be more than a given value
	OperandMORETHAN = NewOperand("%s >= ?", ">=")
	// OperandEQUAL : used to specify that a target entity property should be equal to a given value
	OperandEQUAL = NewOperand("%s = ?", "=")
	// OperandIN : used to specify that a target entity property should be in a list of values
	OperandIN = NewOperand("%s IN (%s)", "IN")
)
View Source
var KindAPPADMIN = RegisterKind(&AppAdmin{}, "")

KindAPPADMIN stores the entity kind associated with 'AppAdmin' entities

View Source
var KindENTITYDIFFERENCE = RegisterKind(&EntityDifference{}, "")

KindENTITYDIFFERENCE stores the entity kind associated with 'EntityDifference' entities

View Source
var KindENTITYLISTDIFFERENCE = RegisterKind(&EntityListDifference{}, "")

KindENTITYLISTDIFFERENCE stores the entity kind associated with 'EntityListDifference' entities

View Source
var KindENTITYSCHEMA = RegisterKind(&EntitySchema{}, "")

KindENTITYSCHEMA stores the entity kind associated with 'EntitySchema' entities

View Source
var KindFIELDDIFFERENCE = RegisterKind(&FieldDifference{}, "")

KindFIELDDIFFERENCE stores the entity kind associated with 'FieldDifference' entities

View Source
var KindJOB = RegisterKind(&Job{}, "")

KindJOB stores the entity kind associated with 'Job' entities

View Source
var KindJOBCONFIGURATION = RegisterKind(&JobConfiguration{}, "")

KindJOBCONFIGURATION stores the entity kind associated with 'JobConfiguration' entities

View Source
var KindJOBPARAM = RegisterKind(&JobParam{}, "")

KindJOBPARAM stores the entity kind associated with 'JobParam' entities

View Source
var KindJOBSEARCH = RegisterKind(&JobSearch{}, "")

KindJOBSEARCH stores the entity kind associated with 'JobSearch' entities

View Source
var KindLINKDIFFERENCE = RegisterKind(&LinkDifference{}, "")

KindLINKDIFFERENCE stores the entity kind associated with 'LinkDifference' entities

View Source
var KindRESOURCE = RegisterKind(&Resource{}, "")

KindRESOURCE stores the entity kind associated with 'Resource' entities

View Source
var KindSWAGGERDOC = RegisterKind(&SwaggerDoc{}, "")

KindSWAGGERDOC stores the entity kind associated with 'SwaggerDoc' entities

View Source
var KindWEBOPERATION = RegisterKind(&WebOperation{}, "")

KindWEBOPERATION stores the entity kind associated with 'WebOperation' entities

View Source
var KindWEBOPERATIONRESPONSE = RegisterKind(&WebOperationResponse{}, "")

KindWEBOPERATIONRESPONSE stores the entity kind associated with 'WebOperationResponse' entities

View Source
var KindWSQUERYPARAM = RegisterKind(&WSQueryParam{}, "")

KindWSQUERYPARAM stores the entity kind associated with 'WSQueryParam' entities

Functions

func AutoMigrate

func AutoMigrate(dbContext DbContext)

AutoMigrate help us do less work in managing the DB migration scripts. It only performs HARMLESS operations, i.e. operations that cannot result in data loss. Amongst these operations: - creation of missing tables - creation of missing link tables - adding of missing columns

  • checking that each property defines a column name (else panic)
  • name consistency checking (this should prevent column renaming) -> the checking should be done by the schema testing

- creation of missing index - extension of column lengths

All the other needed DB operations must be handled by a migration script, that should be written so as to be able to play it anytime, for any version of the app, in order to be free of per-version migration scripts.

func BiContextFromAppServ

func BiContextFromAppServ(appserv *core.Appserv) *appservBiContext

BiContextFromAppServ initialises a new appservBiContext from a given Appserv instance

func BuildUserCacheKey

func BuildUserCacheKey(user IUser) string

BuildUserCacheKey returns a cache key for a given user

func DeleteEntityWithNewTransaction

func DeleteEntityWithNewTransaction(biContext BiContext, toDelete IEntity, checkReferences bool) (Error, IEntity)

DeleteEntityWithNewTransaction is used to delete a given entity in DB It uses a Business transaction to make sure everything goes fine, or fails altogether If checkReferences = true, then if the entity is linked to other entities, then we throw an error. May return an error, and a referencing entity, if there is one.

func DeleteInCache

func DeleteInCache(biContext BiContext, entity IEntity)

DeleteInCache puts the given entity into the local or global cache, depending on the cache policy set for the corresponding entity kind

func EntityFromCache

func EntityFromCache(biContext BiContext, entity IEntity) (cachedEntity interface{}, found bool)

EntityFromCache returns the entity found in cache, if any, based on an entity that should be another version of it, with less properties filled up

func Exec

func Exec(dbContext DbContext, dbOwner DbOwner, queryCtx *QueryExecContext) (sql.Result, error)

Exec : generic implementation

func FetchStringColumn

func FetchStringColumn(dbContext DbContext, entityKind EntityKind, action QueryIDSuffix, query string, args ...interface{}) (results []string)

FetchStringColumn executes a query that should only return an array of string (1 column)

func FetchStringMap

func FetchStringMap(dbContext DbContext, entityKind EntityKind, action QueryIDSuffix, query string, args ...interface{}) (results map[string]string)

FetchStringMap executes a query that should only return a map of string -> string

func FlushEntityCache

func FlushEntityCache(biContext BiContext, entityKind EntityKind)

FlushEntityCache deletes everything from an entity cache

func GenericTestAllSchemas

func GenericTestAllSchemas() (item string, required string, message string, ok bool)

GenericTestAllSchemas tests that all the entities registered through corresponding resources (cf. init function in WS files) have each a correct schema This allows to detect bad entity coding, i.e.: - using non-pointer references to other entities - using non-entity links - using fields of unknown kinds - unqualified entity links, i.e.

  • with no link owner type,
  • missing backref info (can be void, i.e. if no backref)
  • bad backref (not pointing back to the right entity kind)

The returned object is made to be used with the light testing framework goblin:

g := goblin.Goblin(t)
r := GenericTestAllSchemas()
g.Describe(r.Item, func() { g.It(r.Required, func() { g.Assert(!r.Failed).IsTrue(r.Message) }) })

NB: in this function, we can observe the advantage of Go's capability to name returns, since it's way more compact this way

func GetAllOperations

func GetAllOperations() map[string]*WebOperation

GetAllOperations returns the list of all the available operations

func GetEntityKinds

func GetEntityKinds() map[EntityKind]IEntity

GetEntityKinds provides a map containing all the entity kinds involved in the app

func GetHash

func GetHash(entity IEntity) string

GetHash : rebuilds the hash from the hash source

func GetPrimaryReference

func GetPrimaryReference(entity IEntity) string

GetPrimaryReference : returns the entity's primary (ie: functional) reference, which is it's technical ID by default Example: for a user, this can be her username; for a bank account, the banc account number...

func GetSchemaURL

func GetSchemaURL(entityKind EntityKind) core.URL

GetSchemaURL returns the URL allowing to access the schema for the given entity kind

func GetSecondaryDB

func GetSecondaryDB(dbOwner DbOwner, dbID string, check bool) (*sql.DB, error)

GetSecondaryDB : generic implementation

func GetSecondaryDBx

func GetSecondaryDBx(dbOwner DbOwner, dbID string, check bool) (*sqlx.DB, error)

GetSecondaryDBx : generic implementation

func HandlePanic

func HandlePanic(biContext BiContext, err error)

HandlePanic : to handle the errors that should panic

func InsertInCache

func InsertInCache(biContext BiContext, entity IEntity)

InsertInCache puts the given entity into the global cache, if this corresponds to the cache policy set for the corresponding entity kind

func IsEntityExists

func IsEntityExists(biContext BiContext, entity IEntity, minStatus EntityStatus) (bool, EntityID, Error)

IsEntityExists tells us if a given entity already exists in the DB

func IsExists

func IsExists(biContext BiContext, entityKind EntityKind, referenceOrID string, minStatus EntityStatus) (bool, EntityID, Error)

IsExists tells us if an entity with the given kind, and the given ID already exists in the DB

func IsGenericQueryIDSuffix

func IsGenericQueryIDSuffix(queryIDSuffix QueryIDSuffix) bool

IsGenericQueryIDSuffix tells if we are dealing with a query ID suffix or not

func IsIdentical

func IsIdentical(sourceEntity IEntity, targetEntity IEntity, options *ComparisonOptions) bool

IsIdentical tells us if two entities are identical

func IsIdenticalLists

func IsIdenticalLists(sourceEntities []IEntity, targetEntities []IEntity, options *ComparisonOptions) bool

IsIdenticalLists tells us if two entity lists are identical

func IsNilEntity

func IsNilEntity(entity IEntity) bool

IsNilEntity return true if the given entity is nil

func IsReferenced

func IsReferenced(biContext BiContext, entity IEntity) (Error, bool, IEntity)

IsReferenced tells if the provided entity is referenced by another May return a technical error Returns a bool to indicate if there's a referencing entity or not, and the referencing entity if it exists

func ListEntities

func ListEntities(biContext BiContext, entityKind EntityKind, maxNbEntities int, minStatus EntityStatus, loadingID LoadingID) ([]IEntity, Error)

ListEntities retrieves a slice of entities from the DB minStatus defines the status below which the entities are discarded nbEntities defines the maximum number of entities that will be returned func ListEntities(biContext BiContext, entityKind EntityKind, maxNbEntities int, minStatus EntityStatus, loadingPlan ILoadingPlan) ([]IEntity, Error) {

func LogStep

func LogStep(biContext BiContext, formatString string, params ...interface{})

LogStep : used to log step, for example during data initialisation

func LogSubstep

func LogSubstep(biContext BiContext, formatString string, params ...interface{})

LogSubstep : used to log a sub-step, for example during data initialisation

func MakeINClause

func MakeINClause(nbElements int) string

MakeINClause builds a "?,?,...?" string depending on a given number of elements

func Populate

func Populate(biContext BiContext, kind EntityKind, nbEntities int, batchSize int, nbRoutines int, tickPct float64)

Populate randomly generates entities of the given kind, and batch-inserts them into the DB, through concurrent routines. tickPct indicates the interval in percentage between 2 logs of the progression (for instance: 0.1%, 1% or 10%).

func QuerySQL

func QuerySQL(dbContext DbContext, dbOwner DbOwner, queryCtx *QueryExecContext) (*sql.Rows, error)

QuerySQL : generic implementation

func RawExec

func RawExec(dbContext DbContext, dbOwner DbOwner, queryName string, queryString string, values ...interface{}) (sql.Result, error)

RawExec : generic implementation

func RawQuerySQL

func RawQuerySQL(dbContext DbContext, dbOwner DbOwner, queryName string, queryString string, values ...interface{}) (*sql.Rows, error)

RawQuerySQL : generic implementation

func ReadEntity

func ReadEntity(biContext BiContext, entity IEntity, minStatus EntityStatus, loadingID LoadingID) (IEntity, Error)

ReadEntity is a method to read an entity, when it's not loaded yet, having just its kind & ID If allowNil = true, then no error is raised if no entity was found

func ReadReference

func ReadReference(biContext BiContext, entityKind EntityKind, referenceOrID string, forceUseID bool,
	minStatus EntityStatus, loadingID LoadingID) (IEntity, Error)

ReadReference retrieves an entity from the DB, given its ID or primary reference Through this, only a non-deleted entity can be retrieved If forceUseID = true, it means we want to retrieve an entity with its technical ID, even though it defines a primary reference

func RefFromCache

func RefFromCache(biContext BiContext, entityKind EntityKind, entityRefOrID string, loadingID LoadingID) (cachedEntity interface{}, found bool)

RefFromCache returns the entity found in cache, if any, based on an entity kind and an entity ref or ID

func RegisterWebOperations

func RegisterWebOperations(appServ *core.Appserv)

RegisterWebOperations allows to register all the web operations declared in init functions, so that they can be used to respond to requests received by a Vostok app

func RunJobOnDemand

func RunJobOnDemand(childBiContext BiContext, dryrun bool, jobID string, async bool) (*Job, Error)

RunJobOnDemand is meant to be called when we want to run a job besides its scheduled periods, or if its scheduling has been inactivated. Here, the BI context is most probably associated with an app server child, i.e. originated from an HTTP request performed by an admin user. If dryrun = true, then the job may not update anything, depending on how it's implemented. If async = true, then the job is run asynchronously; else synchronously.

func SQLGetCurrencyCode

func SQLGetCurrencyCode(rawBytes *sql.RawBytes) core.CurrencyCode

SQLGetCurrencyCode : mapping SQL -> Go or Vostok type

func SQLGetEmail

func SQLGetEmail(rawBytes *sql.RawBytes) core.Email

SQLGetEmail : mapping SQL -> Go or Vostok type

func SQLGetIEntity

func SQLGetIEntity(rawBytes *sql.RawBytes, entityKind EntityKind) (IEntity, Error)

SQLGetIEntity : mapping SQL -> Go or Vostok type

func SQLGetString

func SQLGetString(rawBytes *sql.RawBytes) string

SQLGetString : mapping SQL -> Go or Vostok type

func SetAllCriteria

func SetAllCriteria(searchEntity ISimpleSearchEntity, criteria ...*SimpleSearchCriterion)

SetAllCriteria sets a list of all the possible criteria out of this entity's fields / links It also initialises the simple search signature. i.e. if only the 1st and 3rd criteria are valued amongst 5 criteria, the signature is "10100"

func ToCamelName

func ToCamelName(entityKind EntityKind) string

ToCamelName returns a given entity kind as a lower-camel-case name

func ToString

func ToString(entity IEntity, allowedLinkDepth int, compact bool) string

ToString returns a string that is used to pretty print an entity, without the technical properties allowedLinkDepth: the depth of links to display compact; if true, then entities do not appear twice in the result string, but as short references

func ToStringFull

func ToStringFull(entity IEntity, allowedLinkDepth int, compact bool) string

ToStringFull returns a string that is used to pretty print an entity, with all the properties allowedLinkDepth: the depth of links to display compact; if true, then entities do not appear twice in the result string, but as short references

func TypeForEntity

func TypeForEntity(entity IEntity) reflect.Type

TypeForEntity returns an entity's type

func TypeForKind

func TypeForKind(entityKind EntityKind) reflect.Type

TypeForKind returns the entity type for a given kind

Types

type AppAdmin

type AppAdmin struct {
	Entity         // is a particular kind of geen entity
	AppName string `db:"-" json:"appName" o*:"the app's name"`
	Version string `db:"-" json:"version" o*:"the app's version"`
}

AppAdmin defines the structure of a App Infos object, i.e. properties & links, plus basic methods

func NewAppAdmin

func NewAppAdmin() *AppAdmin

NewAppAdmin is a shortcut to instantiate a new AppAdmin

func (*AppAdmin) InitSchema

func (thisAppAdmin *AppAdmin) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type AppBiContext

type AppBiContext interface {
	BiContext
	StartGeenBatchJob(batchJobUID core.BatchUID, fn GBatchFunction) Error // starts a scheduled batch function, that will run as configured in the "Batcher" part of the config, with the given function name
	// contains filtered or unexported methods
}

AppBiContext defines a particular BI context, the one created for the app, that wraps the vostok.Appserv instance

func InitApp

func InitApp(opt *AppOptions) (mainServer *c.Appserv, biContext AppBiContext, dryrun bool)

InitApp is the typical and recommended way of starting a geen-based app without forgetting anything

type AppContext

type AppContext interface {
	ILogger // we should be allowed to log anywhere
	//core.IBatcherOwner                                             // we allow to push stuff for batch treatment from here
	GetAppName() string                                            // returns the current app name
	GetAppPath() string                                            // returns the current app path
	GetDescription() string                                        // returns the current app description
	GetVersion() string                                            // returns the current app version
	GetGeenConfig() IGeenConfig                                    // returns the current custom config, i.e. the config belonging to a specific app
	GetMode() core.AppMode                                         // tells is the current mode is: live, prelive, dev, etc...
	IsTestMode() bool                                              // tells if we're in test mode or not
	GetCurrentUser() IUser                                         // the user for whom we're doing stuff right now
	SetCurrentUser(user IUser)                                     // puts the current user into the context
	WarnUser(formatString string, formatParameters ...interface{}) // piles up a warning message that's eventually shown to the user
	// contains filtered or unexported methods
}

AppContext contains the info that may be needed across all the layers

type AppOptions

type AppOptions struct {
	AppName              string                                                         // an app's name for the first logs
	ConfigFile           c.IConfigFile                                                  // your config file
	AutoInsertUsers      yesOrNo                                                        // should we automatically insert users ?
	EnableGenericJobs    yesOrNo                                                        // should we schedule the generic jobs ?
	EnableBatcher        yesOrNo                                                        // are we going to perform asynchronous batch treatments ?
	HashingFunc          func(pwd []byte, salt []byte) ([]byte, error)                  // a hash function for the confidential data such as passwords
	CompareFunc          func(hashedWord []byte, word []byte, salt []byte) error        // a compare function for hashed data such as passwords
	CustomSchemaTestFunc func() (item string, required string, message string, ok bool) // a function that can expand the testing of the entity schemas
}

AppOptions is used to specify an app's options

func (*AppOptions) IsValid

func (thisOpt *AppOptions) IsValid() Error

IsValid allows to check for the validity of options passed to an app

type AuthorizationBearer

type AuthorizationBearer struct {
	AllowedOperations []*WebOperation `db:"allowedOperations" json:"allowedOperations,omitempty" in:"the operations  that this entity has access to"`
}

AuthorizationBearer defines a common structure for all the entity types that are used to implement a complete authorization system

func (*AuthorizationBearer) AddToAllowedOperations

func (thisBearer *AuthorizationBearer) AddToAllowedOperations(ws *WebOperation)

AddToAllowedOperations allows to add a WebOperation instance to those already here; it must check that we're not adding the same WebOperation twice

func (*AuthorizationBearer) GetAllowedOperations

func (thisBearer *AuthorizationBearer) GetAllowedOperations() []*WebOperation

GetAllowedOperations returns the slice of the operations this bearer has access to

func (*AuthorizationBearer) IsOperationAllowed

func (thisBearer *AuthorizationBearer) IsOperationAllowed(ws *WebOperation) bool

IsOperationAllowed tells if a given web operation is allowed for this bearer

type BaseGeenConfig

type BaseGeenConfig struct {
	MaxListSize         int    `json:"MaxListSize"`         // the max size of a list of entities that are fetched from the DB with no particular criterion
	TestSchemasAtLaunch bool   `json:"TestSchemasAtLaunch"` // if true, then the schemas are verified at the starting of the app
	ExampleFilePath     string `json:"ExampleFilePath"`     // the path to the file containing I/O examples to feed the swagger doc
}

BaseGeenConfig is a struct that helps implement a part of what a custom config could be

func (*BaseGeenConfig) GetExampleFilePath

func (thisBaseGeenConfig *BaseGeenConfig) GetExampleFilePath() string

GetExampleFilePath return the path to the file containing I/O examples to feed the swagger doc

func (*BaseGeenConfig) GetMaxListSize

func (thisBaseGeenConfig *BaseGeenConfig) GetMaxListSize() int

GetMaxListSize returns the max size of a list of entities that are fetched from the DB with no particular criterion

func (*BaseGeenConfig) IsTestSchemasAtLaunch

func (thisBaseGeenConfig *BaseGeenConfig) IsTestSchemasAtLaunch() bool

IsTestSchemasAtLaunch returns true when we want the schemas to be verified at the starting of the app

type BaseResponse

type BaseResponse struct {
	Version    string    `json:"version"`
	HTTPStatus int       `json:"status"`
	Messages   []Message `json:"messages"`
}

BaseResponse is the common base for all the responses

func (*BaseResponse) ConcatErrors

func (thisResponse *BaseResponse) ConcatErrors(title string, errors ...Error) IOperationResponse

ConcatErrors allows to pass several errors to be concatenated in a single message

func (*BaseResponse) GetMessages

func (thisResponse *BaseResponse) GetMessages() []Message

GetMessages returns the messages of a operation plural response

func (*BaseResponse) GetStatus

func (thisResponse *BaseResponse) GetStatus() int

GetStatus returns the HTTP status of the response

func (*BaseResponse) Message

func (thisResponse *BaseResponse) Message(gravity Gravity, title string, contentFmt string, contentParams ...interface{}) IOperationResponse

Message allows to add a message to a operation response

type BiContext

type BiContext interface {
	AppContext                                                                                                            // a BI context, is a type of context
	core.IBatcherOwner                                                                                                    // we allow to push stuff for batch treatment from here
	GetDbContext() DbContext                                                                                              // returns a DB context with some info coming from this BI context
	BeginBiTransaction() Error                                                                                            // allows to start a business transaction to handle several business operations that must remain consistent with each other
	IsBiTransactionStarted() bool                                                                                         // tells if a BI transaction is started
	EndBiTransaction(opErr error) Error                                                                                   // allows to end the current business transaction; uses the error that the operations performed during the transaction may have produced
	GetVostokAppToken(appName string, appURL string, user string, password string, timeout time.Duration) (string, error) // GetVostokAppToken retrieves a token to access another Vostok-based app
	NewRoutineBiContext(scopeID string) RoutineBiContext                                                                  // NewRoutineBiContext build a new special BiContext around a new routine, for "go routine" calls
	GetRoutineStats() (currentUse, maxParaUse, totalUse int)                                                              // GetRoutineStats provides a thread-safe access to the routine stats
	StartTrackedJob(jobID string, jfunc scheduledAndTrackedJobFunc) Error                                                 // starts a scheduled job function, that will run as configured in the "Scheduler" part of the config, with the given job ID; each execution is tracked with a Job instance in DB
	// contains filtered or unexported methods
}

BiContext is a context bearing the info required when we're in the WS layer It can allow to persist some stuff, like a current BI transaction

func TestBiContextWithConfig

func TestBiContextWithConfig(configFilePath string, configFileObject core.IConfigFile, initDB bool, verbose bool) BiContext

TestBiContextWithConfig returns an initialised testserv instance Which helps testing the BI / DB code without having to start an HTTP server

type ComparisonOptions

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

ComparisonOptions is a set of options for comparing two entities or lists of entities

func CompareDepth

func CompareDepth(depth int) *ComparisonOptions

CompareDepth instantiates new comparison options

func (*ComparisonOptions) Decr

func (opt *ComparisonOptions) Decr() *ComparisonOptions

Decr clones the given comparison options, but with a 1-step decreased depth

func (*ComparisonOptions) HideNil

func (opt *ComparisonOptions) HideNil() *ComparisonOptions

HideNil forces a nil entity to be displayed with an empty string ""

func (opt *ComparisonOptions) IgnoreLoadedLinks() *ComparisonOptions

IgnoreLoadedLinks allows to ignore the "Loaded Links" property

func (*ComparisonOptions) NoLabels

func (opt *ComparisonOptions) NoLabels() *ComparisonOptions

NoLabels prevents the entity strings from being resumed with their label

func (*ComparisonOptions) NoTech

func (opt *ComparisonOptions) NoTech() *ComparisonOptions

NoTech allows to exclude technical properties from the comparison

func (*ComparisonOptions) RefreshLabels

func (opt *ComparisonOptions) RefreshLabels() *ComparisonOptions

RefreshLabels allows to refresh labels before a comparison

func (*ComparisonOptions) StopAtFirst

func (opt *ComparisonOptions) StopAtFirst() *ComparisonOptions

StopAtFirst allows to stop at the first difference found

type DbContext

type DbContext interface {
	AppContext
	BeginDbTransaction() (*sql.Tx, error)                      // starts a new transaction, and return it
	GetDbName() string                                         // the name of the current DB we're connected to
	IsDBOpen() bool                                            // IsDBOpen tells if the DB has been initialized, or not
	GetUniqueID(counterName string) (int, error)               // GetUniqueID allows to get a unique value associated to the given counter name
	GetSqlLogThreshold() time.Duration                         // GetSqlLogThreshold returns the duration above which SQL executions are logged
	QuerySQL(execContext *QueryExecContext) (*sql.Rows, error) // QuerySQL should execute a query bringing back rows from the DB
	Exec(execContext *QueryExecContext) (sql.Result, error)    // Exec should allow to perform a query to update the DB

	RawQuerySQL(queryName string, queryString string, values ...interface{}) (*sql.Rows, error) // RawQuerySQL should execute a query bringing back rows from the DB - uses a SQL query given as a string, which should be avoided as much as possible
	RawExec(queryName string, queryString string, values ...interface{}) (sql.Result, error)    // RawExec should allow to perform a query to update the DB - uses a SQL query given as a string, which should be avoided as much as possible
	GetSecondaryDB(dbID string, check bool) (*sql.DB, error)                                    // GetSecondaryDB returns a secondary DB, as a *sql.DB instance, if it exists, and has been initialised
	GetSecondaryDBx(dbID string, check bool) (*sqlx.DB, error)                                  // GetSecondaryDBx returns a secondary DB, as a *sqlx.DB instance, if it exists, and has been initialised
	GetSecondaryDbName(id string) string                                                        // the name of the given secondary DB we're connected to
	// contains filtered or unexported methods
}

DbContext defines the main high-level operations besides those of a low-level context This kind of context can be considered "statefull" applicatively speaking, managing transactions for example

type DbOwner

type DbOwner interface {
	QuerySQL(queryAsString string, values ...interface{}) (*sql.Rows, error) // QuerySQL should execute a query bringing back rows from the DB
	Exec(queryAsString string, values ...interface{}) (sql.Result, error)    // Exec should allow to perform a query to update the DB
	GetSecondaryDB(dbID string, check bool) (*sql.DB, error)                 // GetSecondaryDB returns a secondary DB, as a *sql.DB instance, if it exists, and has been initialised
	GetSecondaryDBx(dbID string, check bool) (*sqlx.DB, error)               // GetSecondaryDBx returns a secondary DB, as a *sqlx.DB instance, if it exists, and has been initialised
}

DbOwner defines an interface for objects that possess a handle to a main DB object, and possibly to secondary DBs

type Entity

type Entity struct {
	Kind         EntityKind   `db:"-"              json:"kind"                    io:"the entity's kind"`
	ID           EntityID     `db:"id"             json:"id,omitempty"            o*:"the entity's technical unique identifier"`
	Label        string       `db:"label,128"      json:"label,omitempty"         io:"a label for this entity, to quickly, functionally, identify it"`
	EntityStatus EntityStatus `db:"entityStatus,2" json:"_entityStatus,omitempty" o*:"the entity status"`
	CreatedByID  EntityID     `db:"createdByID"    json:"_createdByID,omitempty"  o*:"the ID of the user that created this entity"`
	CreatedBy    string       `db:"createdBy,128"  json:"_createdBy,omitempty"    o*:"the name of the user that created this entity"`
	Creation     *time.Time   `db:"creation,6"     json:"_creation,omitempty"     o*:"the creation date (Unix time)"`
	DeletedByID  EntityID     `db:"deletedByID"    json:"_deletedByID,omitempty"  o*:"the ID of the user that deleted this entity"`
	DeletedBy    string       `db:"deletedBy,128"  json:"_deletedBy,omitempty"    o*:"the name of the user that deleted this entity"`
	Deletion     *time.Time   `db:"deletion,6"     json:"_deletion,omitempty"     o*:"the deletion date (Unix time)"`
	ModifiedByID EntityID     `db:"modifiedByID"   json:"_modifiedByID,omitempty" o*:"the ID of the latest user that modified this entity"`
	ModifiedBy   string       `db:"modifiedBy,128" json:"_modifiedBy,omitempty"   o*:"the name of the latest user that modified this entity"`
	Modification *time.Time   `db:"modification,6" json:"_modification,omitempty" o*:"the latest modification date (Unix time)"`
	LoadedLinks  []string     `db:"-"              json:"_loadedLinks,omitempty"  o*:"if a link is tagged as 'loaded' then it can be updated"`
	Key          technicalKey `db:"-"              json:"-"                       o*:"a key that uniquely identifies an entity that exists in DB"`

	Hash string `db:"hash,40"        json:"_hash,omitempty"         o*:"the entity's hash"`
	// contains filtered or unexported fields
}

Entity defines a generic implementation of the IEntity interface

func New

func New(entityKind EntityKind) Entity

New helps initialises new entities

func (*Entity) AllLinksOnDepth

func (thisEntity *Entity) AllLinksOnDepth(loadingID LoadingID, depth int) ILoadingPlan

AllLinksOnDepth is used to specify the number of layers in a data tree to load completely. Example: - AllLinksOnDepth(1) allows to load all the links of given entities. - AllLinksOnDepth(1) allows to load all the links of given entities, and their links etc.

func (*Entity) BeforeJSON

func (thisEntity *Entity) BeforeJSON(loadingID LoadingID) IEntity

BeforeJSON can arrange an entity that is going to be marshalled in JSON

func (*Entity) BuildLabel

func (thisEntity *Entity) BuildLabel() (label string, persisted bool)

BuildLabel : has to be be used to refresh the entity's label if it depends on other properties

func (*Entity) CanBeDeleted

func (thisEntity *Entity) CanBeDeleted(biContext BiContext, instore IEntity) Error

CanBeDeleted tells us if the given entity can be updated, and if the changes are acceptable or not

func (*Entity) CanBeRead

func (thisEntity *Entity) CanBeRead(biContext BiContext, loadingID LoadingID) Error

CanBeRead tells us if the given entity can be read (return is nil) or not (return is an error) Wether the entity can be read or not may depend on how it's loaded

func (*Entity) CanBeUpdated

func (thisEntity *Entity) CanBeUpdated(biContext BiContext, instore IEntity) Error

CanBeUpdated tells us if the given entity can be updated, and if the changes are acceptable or not

func (*Entity) ChangeAfterInsert

func (thisEntity *Entity) ChangeAfterInsert(biContext BiContext) Error

ChangeAfterInsert allows to perform specific treatments on the entity after inserting it

func (*Entity) ChangeAfterUpdate

func (thisEntity *Entity) ChangeAfterUpdate(biContext BiContext) Error

ChangeAfterUpdate allows to perform specific treatments on the entity after updating it

func (*Entity) ChangeBeforeCaching

func (thisEntity *Entity) ChangeBeforeCaching(biContext BiContext) Error

ChangeBeforeCaching allows to perform specific treatments on the entity before caching it

func (*Entity) ChangeBeforeInsert

func (thisEntity *Entity) ChangeBeforeInsert(biContext BiContext) Error

ChangeBeforeInsert allows to perform specific treatments on the entity before inserting it

func (*Entity) ChangeBeforeIsExists

func (thisEntity *Entity) ChangeBeforeIsExists(biContext BiContext) Error

ChangeBeforeIsExists allows to perform specific treatments on the entity before checking for its existence

func (*Entity) ChangeBeforeUpdate

func (thisEntity *Entity) ChangeBeforeUpdate(biContext BiContext) Error

ChangeBeforeUpdate allows to perform specific treatments on the entity before updating it

func (*Entity) DefineLoadingPlan

func (thisEntity *Entity) DefineLoadingPlan(loadingID LoadingID) ILoadingPlan

DefineLoadingPlan : build and returns a loading plan for this entity kind and a loading ID

func (*Entity) DoAfterRead

func (thisEntity *Entity) DoAfterRead(biContext BiContext, loadingID LoadingID) Error

DoAfterRead allows to perform some checks or changes right after reading an entity What is done to the entity after reading it may depend on how it's loaded

func (thisEntity *Entity) DoAfterReadLinks(biContext BiContext, loadingID LoadingID) Error

DoAfterReadLinks allows to perform some checks or changes right after reading an entity's links What happens after reading the entity's links may depend on how it's loaded

func (*Entity) Equals

func (thisEntity *Entity) Equals(another IEntity) bool

Equals : tells if this entity is the same as the given one

func (*Entity) FromJSON

func (thisEntity *Entity) FromJSON() Error

FromJSON can transform a entity that has just been unmarshalled from JSONs and perform some controls

func (*Entity) GetCreatedBy

func (thisEntity *Entity) GetCreatedBy() string

GetCreatedBy : returns the name of the user that created this entity

func (*Entity) GetCreatedByID

func (thisEntity *Entity) GetCreatedByID() EntityID

GetCreatedByID : returns the ID of the user that created this entity

func (*Entity) GetCreation

func (thisEntity *Entity) GetCreation() *time.Time

GetCreation : returns the creation date (Unix time)

func (*Entity) GetDeletedBy

func (thisEntity *Entity) GetDeletedBy() string

GetDeletedBy : returns the name of the user that deleted this entity

func (*Entity) GetDeletedByID

func (thisEntity *Entity) GetDeletedByID() EntityID

GetDeletedByID : returns the ID of the user that deleted this entity

func (*Entity) GetDeletion

func (thisEntity *Entity) GetDeletion() *time.Time

GetDeletion : returns the deletion date (Unix time)

func (*Entity) GetEntityStatus

func (thisEntity *Entity) GetEntityStatus() EntityStatus

GetEntityStatus returns returns this entity's status

func (*Entity) GetGlobalCacheDuration

func (thisEntity *Entity) GetGlobalCacheDuration(loadingID LoadingID)

GetGlobalCacheDuration is DEPRECATED. Replaced by GetSharedCachePolicy.

func (*Entity) GetHashSource

func (thisEntity *Entity) GetHashSource() string

GetHashSource : provides the string made from some of the entities properties, that is then hashed by the framework

func (*Entity) GetID

func (thisEntity *Entity) GetID() EntityID

GetID returns returns the entity's ID

func (*Entity) GetKind

func (thisEntity *Entity) GetKind() EntityKind

GetKind returns returns the entity's kind

func (*Entity) GetLabel

func (thisEntity *Entity) GetLabel() string

GetLabel returns returns the entity's label

func (*Entity) GetLoadingBeforeUpdate

func (thisEntity *Entity) GetLoadingBeforeUpdate() string

GetLoadingBeforeUpdate tells how to load the instore version of an entity we're about to update, for controls

func (*Entity) GetLoadingID

func (thisEntity *Entity) GetLoadingID() LoadingID

GetLoadingID : tells us if the entity has been loaded with a particular loading plan, if not empty

func (*Entity) GetLoadingIDForGenericAction

func (thisEntity *Entity) GetLoadingIDForGenericAction(action GenericActionType)

GetLoadingIDForGenericAction allows to specify how to load the data, when using a generic action handler, corresponding to the given action type

func (*Entity) GetModification

func (thisEntity *Entity) GetModification() *time.Time

GetModification : returns the latest modification date (Unix time)

func (*Entity) GetModifiedBy

func (thisEntity *Entity) GetModifiedBy() string

GetModifiedBy : returns the name of the latest user that modified this entity

func (*Entity) GetModifiedByID

func (thisEntity *Entity) GetModifiedByID() EntityID

GetModifiedByID : returns the ID of the latest user that modified this entity

func (*Entity) GetSharedCachePolicy

func (thisEntity *Entity) GetSharedCachePolicy(loadingID LoadingID) (duration time.Duration, flushBeforeUpdate bool)

GetSharedCachePolicy allows to indicate, for all the entities of the same kind how to cache them, i.e. - for how long ? A given duration, or one of these values: SharedCacheDurationNEVER, SharedCacheDurationFOREVER, SharedCacheDurationDEFAULT - should a flush be performed before updating the partitioned cache ?

func (*Entity) GetSpecificSQLQuery

func (thisEntity *Entity) GetSpecificSQLQuery(queryIDSuffix QueryIDSuffix) *SQLQuery

GetSpecificSQLQuery : generic implementation which panics since it has to be implemented in each specific entity type

func (*Entity) InitSchema

func (thisEntity *Entity) InitSchema() *EntitySchema

InitSchema is used to initialize this Entity's schema

func (*Entity) IsDiffed

func (thisEntity *Entity) IsDiffed() bool

IsDiffed indicates if the changes brought through updating the entity should be tracked

func (*Entity) IsHashed

func (thisEntity *Entity) IsHashed() bool

IsHashed : indicates if the entity is to be hashed before being saved

func (*Entity) IsValid

func (thisEntity *Entity) IsValid(biContext BiContext) Error

IsValid is the method through which an entity checks its own validity

func (*Entity) Load

func (thisEntity *Entity) Load(loadingID LoadingID, with ...ILoadingPlan) ILoadingPlan

Load : allows to build a loading plan for this entity

func (*Entity) SetCreatedBy

func (thisEntity *Entity) SetCreatedBy(arg string)

SetCreatedBy : sets the name of the user that created this entity

func (*Entity) SetCreatedByID

func (thisEntity *Entity) SetCreatedByID(arg EntityID)

SetCreatedByID : sets the ID of the user that created this entity

func (*Entity) SetCreation

func (thisEntity *Entity) SetCreation(arg *time.Time)

SetCreation : sets the creation date (Unix time)

func (*Entity) SetDeletedBy

func (thisEntity *Entity) SetDeletedBy(arg string)

SetDeletedBy : sets the name of the user that deleted this entity

func (*Entity) SetDeletedByID

func (thisEntity *Entity) SetDeletedByID(arg EntityID)

SetDeletedByID : sets the ID of the user that deleted this entity

func (*Entity) SetDeletion

func (thisEntity *Entity) SetDeletion(arg *time.Time)

SetDeletion : sets the deletion date (Unix time)

func (*Entity) SetEntityStatus

func (thisEntity *Entity) SetEntityStatus(status EntityStatus)

SetEntityStatus sets this entity's status

func (*Entity) SetID

func (thisEntity *Entity) SetID(ID EntityID)

SetID allows to set the entity's ID

func (*Entity) SetKind

func (thisEntity *Entity) SetKind(kind EntityKind)

SetKind is implemented here once and for all

func (*Entity) SetLabel

func (thisEntity *Entity) SetLabel(label string)

SetLabel allows to set the entity's label

func (*Entity) SetModification

func (thisEntity *Entity) SetModification(arg *time.Time)

SetModification : sets the latest modification date (Unix time)

func (*Entity) SetModifiedBy

func (thisEntity *Entity) SetModifiedBy(arg string)

SetModifiedBy : sets the name of the latest user that modified this entity

func (*Entity) SetModifiedByID

func (thisEntity *Entity) SetModifiedByID(arg EntityID)

SetModifiedByID : sets the ID of the latest user that modified this entity

func (thisEntity *Entity) WithNoLink(loadingID LoadingID) ILoadingPlan

WithNoLink creates an empty loading plan, i.e. with no plan of loading links, but that can allow to specify how to select entities, e.g.: only fields and / or no technical properties etc. WARNING / NB: A loading plan should always be associated with a loading ID. If you do not intend to tweak the plan, with the modifier methods like FieldsOnly, NoTech, etc., then, instead of defining a new plan with this method, you should directly use the loading ID 'LoadingNOLINK'.

type EntityDifference

type EntityDifference struct {
	Entity                               // is a particular kind of geen entity
	SourceEntity     EntityFullReference `db:"sourceEntity,224"    json:"sourceEntity"               o*:"the source entity for the comparison"`
	TargetEntity     EntityFullReference `db:"targetEntity,224"    json:"targetEntity"               o*:"the target entity for the comparison"`
	BasicDifference  string              `` /* 135-byte string literal not displayed */
	FieldDifferences []*FieldDifference  `db:"-"                   json:"fieldDifferences,omitEmpty" o*:"the field differences found between 2 compared entities"`
	LinkDifferences  []*LinkDifference   `db:"-"                   json:"linkDifferences,omitEmpty"  o*:"the link differences found between 2 compared entities"`
}

EntityDifference defines the structure of a ????, i.e. properties & links, plus basic methods NB: an entity reference - which has the form 'kind#primaryRefOrID (label)' should be no more than 224 length: (<= 60) + 1 + (<= 32) + 1 + 1 + (<= 128) + 1

func GetEntityDifference

func GetEntityDifference(sourceEntity IEntity, targetEntity IEntity, options *ComparisonOptions) *EntityDifference

GetEntityDifference returns all the differences found between 2 entities

func (*EntityDifference) DefineLoadingPlan

func (thisDiff *EntityDifference) DefineLoadingPlan(loadingID LoadingID) ILoadingPlan

DefineLoadingPlan : build and returns a loading plan for this entity kind and a loading ID

func (*EntityDifference) HasDifference

func (thisDiff *EntityDifference) HasDifference() bool

HasDifference tells if the given entity diff bears differences

func (*EntityDifference) InitSchema

func (thisDiff *EntityDifference) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type EntityField

type EntityField struct {
	EntityProperty                  // an EntityField is a particular kind of EntityProperty
	MaxLength        int            `` /* 164-byte string literal not displayed */
	Precision        int            `json:"precision,omitempty"        o*:"for real numbers, the number of decimals"`
	MinValue         float64        `json:"minValue,omitempty"         o*:"the minimal numeric value"`
	MaxValue         float64        `json:"maxValue,omitempty"         o*:"the maximal numeric value"`
	PossibleValues   map[int]string `json:"possibleValues,omitempty"   o*:"the values this field can have"`
	Unique           bool           `json:"unique,omitempty"           o*:"if true, then it means this field's values in the DB must be unique"`
	PrimaryReference bool           `` /* 160-byte string literal not displayed */
	RawType          reflect.Type   `` /* 130-byte string literal not displayed */
	EnumValues       []int          `json:"-"                          o*:"the list of all the enum values, as integers"`
	Transformed      bool           `` /* 132-byte string literal not displayed */
}

EntityField is used to capture all the relevant info about an entity field: name, type, max value, required, etc.

func (*EntityField) GetMaskedSQLValue

func (thisField *EntityField) GetMaskedSQLValue(sourceEntityAsElemValue reflect.Value) interface{}

GetMaskedSQLValue returns, for a given entity, the property's value as suitable for a SQL column, if is not confidential; if it is, then the value is obfuscated; this serves for debbugging, logging purposes

func (*EntityField) GetSQLValue

func (thisField *EntityField) GetSQLValue(sourceEntityAsElemValue reflect.Value) interface{}

GetSQLValue retrieves the value associated with a given entity field, from a source entity, given as a Value (through reflect.ValueOf().Elem()) and returns a value that can fit in a SQL column

func (*EntityField) GetStringValue

func (thisField *EntityField) GetStringValue(sourceEntityAsElemValue reflect.Value) string

GetStringValue retrieves the value associated with a given entity field, from a source entity, given as a string

func (*EntityField) IsAmount

func (thisField *EntityField) IsAmount() bool

IsAmount tells if this field corresponds to an amount of money

func (*EntityField) IsBoolean

func (thisField *EntityField) IsBoolean() bool

IsBoolean tells if this field is a boolean

func (*EntityField) IsDate

func (thisField *EntityField) IsDate() bool

IsDate tells if this field corresponds to a date

func (*EntityField) IsEnum

func (thisField *EntityField) IsEnum() bool

IsEnum tells if this field contains an enum or a list of enums

func (*EntityField) IsEnumList

func (thisField *EntityField) IsEnumList() bool

IsEnumList tells if this field contains a list of enums

func (*EntityField) IsInt

func (thisField *EntityField) IsInt() bool

IsInt tells if this field corresponds to a 32-bits int

func (*EntityField) IsKind

func (thisField *EntityField) IsKind() bool

IsKind tells if this field corresponds to the "Kind" field

func (*EntityField) IsPersisted

func (thisField *EntityField) IsPersisted() bool

IsPersisted returns true if the field is persisted, i.e. exists as a colum in the DB; else, it means the property is probably a technical one

func (*EntityField) IsReal

func (thisField *EntityField) IsReal() bool

IsReal tells if this field corresponds to a real number

func (*EntityField) IsString

func (thisField *EntityField) IsString() bool

IsString tells if the field correspond to a string kind

func (*EntityField) IsTransformed

func (thisField *EntityField) IsTransformed() bool

IsTransformed tells if this field's value is transformed before being persisted

func (*EntityField) IsZeroValue

func (thisField *EntityField) IsZeroValue(sourceEntityAsElemValue reflect.Value) bool

IsZeroValue tells if the value associated with the given field is the zero value

func (*EntityField) NoEdit

func (thisField *EntityField) NoEdit() *EntityField

NoEdit sets an entity field to being not editable

func (*EntityField) SetConfidential

func (thisField *EntityField) SetConfidential() IEntityProperty

SetConfidential : sets the confidential mode

func (*EntityField) SetPrimaryReference

func (thisField *EntityField) SetPrimaryReference() *EntityField

SetPrimaryReference makes this field's values unique, DB-wise

func (*EntityField) SetRandomValue

func (thisField *EntityField) SetRandomValue(source rand.Source, sourceEntityAsElemValue reflect.Value)

SetRandomValue sets a (pseudo-)randomly generated value into the receiver entity field This function should always use SetStringValue, as a way to test this latter function.

func (*EntityField) SetRequired

func (thisField *EntityField) SetRequired() *EntityField

SetRequired makes this field unable to be empty, DB-wise

func (*EntityField) SetStringValue

func (thisField *EntityField) SetStringValue(sourceEntityAsElemValue reflect.Value, valueAsString string) Error

SetStringValue allows to change a property's value, thanks to a value given as a string

func (*EntityField) SetTransformed

func (thisField *EntityField) SetTransformed() *EntityField

SetTransformed tells if this field's value is transformed before being persisted

func (*EntityField) SetUnique

func (thisField *EntityField) SetUnique() *EntityField

SetUnique makes this field's values unique, DB-wise

type EntityFullReference

type EntityFullReference EntityReference

EntityFullReference is a special string that is an entity reference + an entity label Ex: user::admin (the admin user), usergroup::DEV (the developers), project::127 (project HAND)

func RandomEntityFullReference

func RandomEntityFullReference(source rand.Source) EntityFullReference

RandomEntityFullReference returns a randomly built EntityFullReference as a string

func ToEntityFullReference

func ToEntityFullReference(entity IEntity) EntityFullReference

ToEntityFullReference returns a string that is used to quickly print an entity

type EntityID

type EntityID uint64

EntityID is used to uniquely identify entities

type EntityKind

type EntityKind string

EntityKind : this is a string representation of an entity kind, that can be used in URLs for example

func GetImplemKind

func GetImplemKind(someInterface reflect.Type) EntityKind

GetImplemKind returns the first entity kind that implements the given interface

func GetResultKind

func GetResultKind(searchEntity ISimpleSearchEntity) EntityKind

GetResultKind returns the kind of the entities found with the given search

func RandomKind

func RandomKind(source rand.Source) EntityKind

RandomKind randomly returns an entity kind, amongst those that are registred

func RegisterKind

func RegisterKind(entity IEntity, customKindName string) EntityKind

RegisterKind initialises a Kind from a given entity instance, which we call "base entity". If customKindName != "", then this given custom kind name is used in place of a name automatically built from the entity's struct name

func (EntityKind) PartitionName

func (thisKind EntityKind) PartitionName() string

PartitionName : Implementing ICachePartition

type EntityLink struct {
	EntityProperty                       // an EntityLink is a particular kind of EntityProperty
	TargetKind          EntityKind       `json:"targetKind"    o*:"the entity kind (as a string) pointed by this link"`
	BackRef             EntityPropertyID `json:"backref"       o*:"the name of the link on the target entity that points back to this entity"`
	BackRefLink         *EntityLink      `json:"-"             o*:"the entity link corresponding to backref given by its ID"`
	LinkDirection       linkDirection    `json:"-"             o*:"the direction of the link"`
	LinkDirectionString string           `json:"linkDirection" o*:"the direction of the link"`
	TargetKindSchemaURL core.URL         `json:"schemaURL"     o*:"the URL to the schema for the entity kind pointed by this link"`
	LinkTableName       string           `json:"-"             o*:"the name of the table that persist this link if it is multiple"`
	SourceColumnName    string           `json:"-"             o*:"the name of the column in the link table that holds the ID of the source entity"`
	TargetColumnName    string           `json:"-"             o*:"the name of the column in the link table that holds the ID of the target entity"`
	PersistencyMode     persistencyMode  `json:"-"             o*:"0 = undefined, 1 = not persisted, 2 = directly, 3 = indirectly (i.e. the backref IS persisted)"`
}

EntityLink is used to capture all the relevant info about an entity link: the associated entity kind, the cardinality, the path to the corresponding schema, etc.

func GetResultLink(searchEntity ISimpleSearchEntity) *EntityLink

GetResultLink returns the link corresponding to the result link ID

func (*EntityLink) AttachEntity

func (thisLink *EntityLink) AttachEntity(sourceEntityAsElemValue reflect.Value, targetEntityAsValue reflect.Value)

AttachEntity adds the given target entity to the given source entity through this link

func (thisLink *EntityLink) GetBackrefLink() *EntityLink

GetBackrefLink returns the entity link corresponding to the given

func (*EntityLink) GetLinkTableName

func (thisLink *EntityLink) GetLinkTableName() string

GetLinkTableName returns the name of the table that persist this link, if it is multiple and if it is DIRECTLY persisted, i.e. if the entity associated with the current schema is at the SOURCE END of the link, not the TARGET one.

func (*EntityLink) GetLinkTableSourceColumn

func (thisLink *EntityLink) GetLinkTableSourceColumn() string

GetLinkTableSourceColumn returns the name of the column in the link table that holds the ID of the source entity

func (*EntityLink) GetLinkTableTargetColumn

func (thisLink *EntityLink) GetLinkTableTargetColumn() string

GetLinkTableTargetColumn returns the name of the column in the link table that holds the ID of the target entity

func (*EntityLink) GetLinkedEntities

func (thisLink *EntityLink) GetLinkedEntities(sourceEntityAsElemValue reflect.Value) interface{}

GetLinkedEntities retrieves the entities pointed by a given entity link, from a source entity, given as a Value (through reflect.ValueOf().Elem()) NB: the result is an interface{}

func (*EntityLink) GetLinkedEntitiesAsValue

func (thisLink *EntityLink) GetLinkedEntitiesAsValue(sourceEntityAsElemValue reflect.Value) reflect.Value

GetLinkedEntitiesAsValue retrieves the entities pointed by a given entity link, from a source entity, given as a Value (through reflect.ValueOf().Elem()) NB: the result is a reflect.Value, ready to be manipulated with reflection

func (*EntityLink) GetLinkedEntity

func (thisLink *EntityLink) GetLinkedEntity(sourceEntityAsElemValue reflect.Value) IEntity

GetLinkedEntity retrieves the entity pointed by a given entity link

func (*EntityLink) GetLinkedEntityAsValue

func (thisLink *EntityLink) GetLinkedEntityAsValue(sourceEntityAsElemValue reflect.Value) reflect.Value

GetLinkedEntityAsValue retrieves the entity pointed by a given entity link, from a source entity, given as a Value (through reflect.ValueOf().Elem())

func (*EntityLink) GetMaskedSQLValue

func (thisLink *EntityLink) GetMaskedSQLValue(sourceEntityAsElemValue reflect.Value) interface{}

GetMaskedSQLValue returns, for a given entity, the property's value as suitable for a SQL column, if is not confidential; if it is, then the value is obfuscated; this serves for debbugging, logging purposes

func (*EntityLink) GetSQLValue

func (thisLink *EntityLink) GetSQLValue(sourceEntityAsElemValue reflect.Value) interface{}

GetSQLValue retrieves the ID of the entity

func (*EntityLink) GetSortedLinkedEntities

func (thisLink *EntityLink) GetSortedLinkedEntities(sourceEntityAsElemValue reflect.Value) []IEntity

GetSortedLinkedEntities retrieves the entities pointed by a given entity link, from a source entity, and returns them as a slice, with the entities sorted by their entity reference

func (*EntityLink) GetStringValue

func (thisLink *EntityLink) GetStringValue(sourceEntityAsElemValue reflect.Value) string

GetStringValue retrieves the value associated with a given entity link, from a source entity, given as a string

func (*EntityLink) GetUnsortedLinkedEntities

func (thisLink *EntityLink) GetUnsortedLinkedEntities(sourceEntityAsElemValue reflect.Value) []IEntity

GetUnsortedLinkedEntities retrieves the entities pointed by a given entity link, from a source entity, and returns them as a slice NB: it's only useful when we cannot use reflection. For performance, it's better not to use this function.

func (*EntityLink) IsChildToParent

func (thisLink *EntityLink) IsChildToParent() bool

IsChildToParent tells if that this link goes from a child entity to its parent

func (*EntityLink) IsDirectlyPersisted

func (thisLink *EntityLink) IsDirectlyPersisted() bool

IsDirectlyPersisted : when the link is directly persisted, single or multiple

func (*EntityLink) IsMultipleDirectlyPersisted

func (thisLink *EntityLink) IsMultipleDirectlyPersisted() bool

IsMultipleDirectlyPersisted : when there's a link table, and the entity persisting this link has its ID in the first (source) column Example: a user group's members (user) => column userGroup_id in table "link_userGroup_members"

func (*EntityLink) IsMultipleIndirectlyPersisted

func (thisLink *EntityLink) IsMultipleIndirectlyPersisted() bool

IsMultipleIndirectlyPersisted : when there's a link table, and the entity persisting this link has its ID in the second (target) column Example: a user's groups () => column user_id in table "link_userGroup_members"

func (*EntityLink) IsOneWay

func (thisLink *EntityLink) IsOneWay() bool

IsOneWay tells if that this link is a one directional one

func (*EntityLink) IsParentFromChildren

func (thisLink *EntityLink) IsParentFromChildren() bool

IsParentFromChildren tells if that this link goes from a parent entity back to its children

func (*EntityLink) IsSingleDirectlyPersisted

func (thisLink *EntityLink) IsSingleDirectlyPersisted() bool

IsSingleDirectlyPersisted : when an entity holds a column for ths link Example: a user group's main contact (user) => column mainContact_id in table "userGroup"

func (*EntityLink) IsSingleIndirectlyPersisted

func (thisLink *EntityLink) IsSingleIndirectlyPersisted() bool

IsSingleIndirectlyPersisted : when the entity's ID is held by another entity in one of its column. Example: a user's responsible-for-groups => column mainContact_id in table "userGroup"

func (*EntityLink) IsSomehowPersisted

func (thisLink *EntityLink) IsSomehowPersisted() bool

IsSomehowPersisted : this link is somehow persisted in the DB

func (*EntityLink) IsSourceToTarget

func (thisLink *EntityLink) IsSourceToTarget() bool

IsSourceToTarget tells if that this link goes from a source entity to its target

func (*EntityLink) IsTargetFromSource

func (thisLink *EntityLink) IsTargetFromSource() bool

IsTargetFromSource tells if that this link goes from a target back to its source

func (*EntityLink) IsZeroValue

func (thisLink *EntityLink) IsZeroValue(sourceEntityAsElemValue reflect.Value) bool

IsZeroValue tells if the value associated with the given link is the zero value

func (*EntityLink) SetChildToParent

func (thisLink *EntityLink) SetChildToParent() *EntityLink

SetChildToParent is used to tell that this link goes from a child entity to its parent

func (*EntityLink) SetConfidential

func (thisLink *EntityLink) SetConfidential() IEntityProperty

SetConfidential : sets the confidential mode

func (*EntityLink) SetOneWay

func (thisLink *EntityLink) SetOneWay() *EntityLink

SetOneWay is used to tell that this link is a one directional one

func (*EntityLink) SetParentFromChildren

func (thisLink *EntityLink) SetParentFromChildren() *EntityLink

SetParentFromChildren is used to tell that this link goes from a parent entity back to its children

func (*EntityLink) SetRequired

func (thisLink *EntityLink) SetRequired() *EntityLink

SetRequired makes this link unable to be empty, DB-wise

func (*EntityLink) SetSourceToTarget

func (thisLink *EntityLink) SetSourceToTarget() *EntityLink

SetSourceToTarget is used to tell that this link goes from a source entity to its target

func (*EntityLink) SetStringValue

func (thisLink *EntityLink) SetStringValue(sourceEntityAsElemValue reflect.Value, valueAsString string) Error

SetStringValue allows to change a property's value, thanks to a value given as a string

func (*EntityLink) SetTargetFromSource

func (thisLink *EntityLink) SetTargetFromSource() *EntityLink

SetTargetFromSource is used to tell that this link goes from a target back to its source

func (*EntityLink) WithBackRef

func (thisLink *EntityLink) WithBackRef(propertyID EntityPropertyID) *EntityLink

WithBackRef allows to set the backref for this link

type EntityListDifference

type EntityListDifference struct {
	Entity                            // is a particular kind of geen entity
	Added         []*EntityDifference `json:"added"    o*:"the references of the entities added into the examined entity list"`
	Removed       []*EntityDifference `json:"removed"  o*:"the references of the entities removed from the examined entity list"`
	EntityChanges []*EntityDifference `json:"-"        o*:"the differences for the entities before / after the changes performed on the examined entity list"`
}

EntityListDifference defines the structure of a ????, i.e. properties & links, plus basic methods

func GetListDifference

func GetListDifference(sourceEntities []IEntity, targetEntities []IEntity, options *ComparisonOptions) *EntityListDifference

GetListDifference builds an entity list difference by comparing 2 lists of entities

func NewEntityListDifference

func NewEntityListDifference() *EntityListDifference

NewEntityListDifference is a shortcut to instantiate a new EntityListDifference

func (*EntityListDifference) HasDifference

func (thisDiff *EntityListDifference) HasDifference() bool

HasDifference tells if an entity list difference show some difference

func (*EntityListDifference) InitSchema

func (thisEntityListDifference *EntityListDifference) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type EntityProperty

type EntityProperty struct {
	OwnerSchema        *EntitySchema    `json:"-"                      o*:"the schema this property belongs to"`
	PropertyID         EntityPropertyID `json:"-"                      o*:"the (normally) unique entity property ID"`
	PropertyType       PropertyType     `json:"-"                      o*:"the type of the property"`
	PropertyTypeString string           `json:"propertyType,omitempty" o*:"the type of the property (as a string)"`
	Multiple           bool             `json:"multiple"               o*:"true when this is a link to several target entities"`
	JSONName           string           `json:"jsonName"               o*:"the JSON name of the property"`
	Name               string           `json:"-"                      o*:"the name of the entity's property"`
	Description        string           `json:"description"            o*:"the description of the entity's property"`
	IOType             ioType           `json:"ioType"                 o*:"the field type: is it an input or output field ?"`
	Required           bool             `` /* 217-byte string literal not displayed */
	Editable           bool             `json:"editable"               o*:"indicates if this property can be changed by a user or not"`
	OmitEmpty          bool             `json:"omitEmpty"              o*:"if true, then the property is not put into any JSON output if null/0/void"`
	Immutable          bool             `json:"immutable"              o*:"if true, then once set, the value cannot be changed"`
	Confidential       bool             `json:"-"                      o*:"if true, then a column name different from the lower case field name is allowed"`
	// contains filtered or unexported fields
}

EntityProperty is used to capture the generic meta info about an entity property, whereas it is a an entity field, or an entity link

func (*EntityProperty) GetColumnName

func (thisProperty *EntityProperty) GetColumnName() string

GetColumnName is the name of the column in which the property is persisted, if it's persisted directly on the entity

func (*EntityProperty) GetName

func (thisProperty *EntityProperty) GetName() string

GetName returns the name of the property

func (*EntityProperty) GetValue

func (thisProperty *EntityProperty) GetValue(sourceEntityAsElemValue reflect.Value) reflect.Value

GetValue retrieves the value associated with a given entity property, from a source entity, given as a Value (through reflect.ValueOf().Elem())

func (*EntityProperty) HideInSwagger

func (thisProperty *EntityProperty) HideInSwagger() *EntityProperty

func (*EntityProperty) IsConfidential

func (thisProperty *EntityProperty) IsConfidential() bool

IsConfidential : if true then the property should be fetched from the DB with extra care

func (*EntityProperty) IsCoreProperty

func (thisProperty *EntityProperty) IsCoreProperty() bool

IsCoreProperty tells us if this property is technical

func (*EntityProperty) IsGenericProperty

func (thisProperty *EntityProperty) IsGenericProperty() bool

IsGenericProperty tells us if this property is generic

func (*EntityProperty) IsIdentificationProperty

func (thisProperty *EntityProperty) IsIdentificationProperty() bool

IsIdentificationProperty tells us if this property is used to identify an entity

func (*EntityProperty) IsImmutable

func (thisProperty *EntityProperty) IsImmutable() bool

IsImmutable tells us if this property is immutable, i.e. cannot be changed once set

func (*EntityProperty) IsInputProperty

func (thisProperty *EntityProperty) IsInputProperty() bool

IsInputProperty : can this property be expected as a user input ?

func (thisProperty *EntityProperty) IsLink() bool

IsLink tells us if this property is a link; if not, it's a field

func (*EntityProperty) IsMandatoryInput

func (thisProperty *EntityProperty) IsMandatoryInput() bool

IsMandatoryInput : must the user fill this property ?

func (*EntityProperty) IsPersistencyProperty

func (thisProperty *EntityProperty) IsPersistencyProperty() bool

IsPersistencyProperty tells us if this property is related to persistency management

func (*EntityProperty) IsPureTechnicalProperty

func (thisProperty *EntityProperty) IsPureTechnicalProperty() bool

IsPureTechnicalProperty tells us if this property is purely technical, i.e. a technical property that cannot really be used for identification

func (*EntityProperty) IsRequiredInDB

func (thisProperty *EntityProperty) IsRequiredInDB() bool

IsRequiredInDB tells us if this property is required, for the owner entity to be persisted

func (*EntityProperty) IsTechnicalProperty

func (thisProperty *EntityProperty) IsTechnicalProperty() bool

IsTechnicalProperty tells us if this property is technical

func (*EntityProperty) SetImmutable

func (thisProperty *EntityProperty) SetImmutable() *EntityProperty

SetImmutable sets immutable to true

func (*EntityProperty) SetInSwaggerForAdmins

func (thisProperty *EntityProperty) SetInSwaggerForAdmins() *EntityProperty

func (*EntityProperty) SetNotPersisted

func (thisProperty *EntityProperty) SetNotPersisted() *EntityProperty

SetNotPersisted makes the current property actually not persisted

func (*EntityProperty) SetValue

func (thisProperty *EntityProperty) SetValue(sourceEntityAsElemValue reflect.Value, valueToSet reflect.Value)

SetValue allows to change a link's value (given as a Value) for an entity given as a value

func (*EntityProperty) ShowInSwagger

func (thisProperty *EntityProperty) ShowInSwagger() *EntityProperty

type EntityPropertyID

type EntityPropertyID string

EntityPropertyID : an entity property ID has this form: entityKind$propertyName. e.g. "user$Description"

const (
	FieldEntityDifferenceSOURCEENTITY    EntityPropertyID = "entitydifference$SourceEntity"
	FieldEntityDifferenceTARGETENTITY    EntityPropertyID = "entitydifference$TargetEntity"
	LinkEntityDifferenceFIELDDIFFERENCES EntityPropertyID = "entitydifference$FieldDifferences"
	LinkEntityDifferenceLINKDIFFERENCES  EntityPropertyID = "entitydifference$LinkDifferences"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	FieldEntityDiffSearchENTITYREF  EntityPropertyID = "entitydiffsearch$EntityRef"
	LinkEntityDiffSearchDIFFERENCES EntityPropertyID = "entitydiffsearch$Differences"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	FieldDifferenceOWNER       EntityPropertyID = "fielddifference$Owner"
	FieldDifferenceVALUEBEFORE EntityPropertyID = "fielddifference$ValueBefore"
	FieldDifferenceVALUEAFTER  EntityPropertyID = "fielddifference$ValueAfter"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	FieldJobUID      EntityPropertyID = "job$UID"
	FieldJobSTARTED  EntityPropertyID = "job$Started"
	LinkJobJOBCONFIG EntityPropertyID = "job$JobConfig"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	FieldJobConfigurationUID     EntityPropertyID = "jobconfiguration$UID"
	LinkJobConfigurationPARAMS   EntityPropertyID = "jobconfiguration$Params"
	LinkJobConfigurationPASTJOBS EntityPropertyID = "jobconfiguration$PastJobs"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	FieldJobParamNAME     EntityPropertyID = "jobparam$Name"
	LinkJobParamJOBCONFIG EntityPropertyID = "jobparam$JobConfig"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	FieldJobSearchJOBUID EntityPropertyID = "jobsearch$JobUID"
	LinkJobSearchJOBS    EntityPropertyID = "jobsearch$Jobs"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	LinkDifferenceOWNER                   EntityPropertyID = "linkdifference$Owner"
	LinkDifferenceINDEPTHFIELDDIFFERENCES EntityPropertyID = "linkdifference$InDepthFieldDifferences"
	LinkDifferenceINDEPTHLINKDIFFERENCES  EntityPropertyID = "linkdifference$InDepthLinkDifferences"
)

Entity property IDs, allowing referencing properties of a given entity type from another entity type

const (
	FieldResourceRESOURCEKIND EntityPropertyID = "resource$ResourceKind"
	LinkResourceOPERATIONS    EntityPropertyID = "resource$Operations"
)

Entity property IDs, allowing referencing properties of a given entity kind from another entity kind

const (
	FieldWebOperationNAME    EntityPropertyID = "weboperation$Name"
	LinkWebOperationRESOURCE EntityPropertyID = "weboperation$Resource"
)

Entity property IDs, allowing referencing properties of a given entity kind from another entity kind

type EntityReference

type EntityReference string

EntityReference is a special string that contain a minimalist representation of an entity Ex: user::admin, usergroup::DEV, project::127

func ToEntityReference

func ToEntityReference(entity IEntity) EntityReference

ToEntityReference returns a string that is used to VERY quickly print out an entity

type EntitySchema

type EntitySchema struct {
	Entity                                        // a schema is a particular kind of Entity - it cannot be persisted in DB, but can be JSONified and sent to a web client
	EntityKind  EntityKind                        `json:"entityKind"  o*:"the kind of entity this schema is associated with"`
	Fields      map[EntityPropertyID]*EntityField `json:"fields"      o*:"the properties of the associated entity kind"`
	Links       map[EntityPropertyID]*EntityLink  `json:"links"       o*:"the links of the associated entity kind"`
	Description string                            `json:"description" o*:"this entity kind's description'"`
	// contains filtered or unexported fields
}

EntitySchema allows to capture and share all the meta info about an Entity type

func GetPublishedSchema

func GetPublishedSchema(entityKind EntityKind) (publishedSchema *EntitySchema)

GetPublishedSchema returns a version of a schema that can be shown through an API call. It strips off the properties that are not JSONified. It also strips off the non-core generic properties is the entity kind is not persisted, since they're useless in that case.

func GetSchema

func GetSchema(entityKind EntityKind) (schema *EntitySchema)

GetSchema returns a schema for a given entity kind It consists in retrieving the schema from the cache, or initializing it with InitSchema

func NewSchema

func NewSchema(entityKind EntityKind) *EntitySchema

NewSchema browses an entity's properties to automatically initialise a schema

func (*EntitySchema) AllowCustomTableName

func (thisSchema *EntitySchema) AllowCustomTableName() *EntitySchema

AllowCustomTableName allows to set a custom table name

func (*EntitySchema) CheckJSONNamesWith

func (thisSchema *EntitySchema) CheckJSONNamesWith(checkerFunc func(string) string) *EntitySchema

CheckJSONNamesWith allows to change the default JSON name checker, which is vostok.PascalToCamel

func (*EntitySchema) EntityDesc

func (thisSchema *EntitySchema) EntityDesc(desc string) *EntitySchema

EntityDesc allows to provide a description for this entity kind

func (*EntitySchema) Field

func (thisSchema *EntitySchema) Field(propertyID EntityPropertyID) *EntityField

Field returns a schema's entity field, given its property ID

func (*EntitySchema) FieldByName

func (thisSchema *EntitySchema) FieldByName(fieldName string) *EntityField

FieldByName returns a schema's entity field, given its case-sentitive name

func (*EntitySchema) GetImmutableProperties

func (thisSchema *EntitySchema) GetImmutableProperties() []IEntityProperty

GetImmutableProperties returns the sorted list of the immutable properties, which is a subset of the persisted properties

func (thisSchema *EntitySchema) GetLinkTablePersistedLinks() []*EntityLink

GetLinkTablePersistedLinks returns the sorted list of the fields that are persisted

func (*EntitySchema) GetMaxPropertyLength

func (thisSchema *EntitySchema) GetMaxPropertyLength() int

GetMaxPropertyLength returns the maximum length the property names associated with this schema

func (thisSchema *EntitySchema) GetMultipleDirectlyPersistedLinks() []*EntityLink

GetMultipleDirectlyPersistedLinks returns the sorted list of the fields that are persisted

func (*EntitySchema) GetPersistedFields

func (thisSchema *EntitySchema) GetPersistedFields() []IEntityProperty

GetPersistedFields returns the sorted list of the fields that are persisted

func (*EntitySchema) GetPersistedNonTechnicalFields

func (thisSchema *EntitySchema) GetPersistedNonTechnicalFields() []IEntityProperty

GetPersistedNonTechnicalFields returns the non technical properties

func (*EntitySchema) GetPersistedNonTechnicalProperties

func (thisSchema *EntitySchema) GetPersistedNonTechnicalProperties() []IEntityProperty

GetPersistedNonTechnicalProperties returns the non technical properties

func (*EntitySchema) GetPersistedProperties

func (thisSchema *EntitySchema) GetPersistedProperties() []IEntityProperty

GetPersistedProperties returns the sorted list of the properties persisted within the entity table, i.e. the persisted single links + the persisted fields

func (*EntitySchema) GetPersonalInfos

func (thisSchema *EntitySchema) GetPersonalInfos() []IEntityProperty

GetPersonalInfos returns the personal infos

func (*EntitySchema) GetPrimaryReferenceField

func (thisSchema *EntitySchema) GetPrimaryReferenceField() *EntityField

GetPrimaryReferenceField returns the field used as a primary reference If NoPrimaryReference() has been used on the schema, then the primary reference is the technical ID

func (*EntitySchema) GetRequiredFields

func (thisSchema *EntitySchema) GetRequiredFields() []*EntityField

GetRequiredFields returns the required fields, i.e. the fields that cannot lead to duplicate values in their corresponding columns initialising it, the first time we need it

func (thisSchema *EntitySchema) GetSingleDirectlyPersistedLinks() []*EntityLink

GetSingleDirectlyPersistedLinks returns the sorted list of the fields that are persisted

func (*EntitySchema) GetSortedFields

func (thisSchema *EntitySchema) GetSortedFields() []*EntityField

GetSortedFields returns the sorted list of the fields

func (thisSchema *EntitySchema) GetSortedLinks() []*EntityLink

GetSortedLinks returns the sorted list of the links

func (*EntitySchema) GetTable

func (thisSchema *EntitySchema) GetTable() string

GetTable returns the name of the table associated with this schema

func (*EntitySchema) GetUniqueFields

func (thisSchema *EntitySchema) GetUniqueFields() []*EntityField

GetUniqueFields returns the unique fields, i.e. the fields that cannot lead to duplicate values in their corresponding columns initialising it, the first time we need it

func (*EntitySchema) HideInSwagger

func (thisSchema *EntitySchema) HideInSwagger() *EntitySchema

func (*EntitySchema) InitSchema

func (thisSchema *EntitySchema) InitSchema() *EntitySchema

InitSchema is used to initialize this Entity's schema

func (*EntitySchema) IsAllPersonal

func (thisSchema *EntitySchema) IsAllPersonal() bool

IsAllPersonal indicates if the whole entity is personal info

func (*EntitySchema) IsPersisted

func (thisSchema *EntitySchema) IsPersisted() bool

IsPersisted returns true if the entity is persisted, i.e. exists as a colum in the DB; else, it means the property is probably a technical one

func (*EntitySchema) IsPersonal

func (thisSchema *EntitySchema) IsPersonal(propertyID EntityPropertyID) bool

IsPersonal tells us if a property is personal info

func (thisSchema *EntitySchema) Link(propertyID EntityPropertyID) *EntityLink

Link returns a schema's entity link, given its property ID

func (*EntitySchema) LinkByName

func (thisSchema *EntitySchema) LinkByName(linkName string) *EntityLink

LinkByName returns a schema's entity link, given its case-sentitive name

func (*EntitySchema) NoDeletionTracking

func (thisSchema *EntitySchema) NoDeletionTracking() *EntitySchema

TrackOnlyCreation indicates that we want to know only who created and last updated these entities, and when

func (*EntitySchema) NoPersonalInfo

func (thisSchema *EntitySchema) NoPersonalInfo() *EntitySchema

NoPersonalInfo allows to indicate that the current entity type does not contain any personal info

func (*EntitySchema) NoPrimaryReference

func (thisSchema *EntitySchema) NoPrimaryReference() *EntitySchema

NoPrimaryReference indicates that the entities will not be fetched thanks to a functional reference (like an order reference, a username...), but only through the technical ID

func (*EntitySchema) Property

func (thisSchema *EntitySchema) Property(propertyID EntityPropertyID) IEntityProperty

Property returns a property, given it's ID. It can be a field or a link. Panics if not found.

func (*EntitySchema) RemoveLabel

func (thisSchema *EntitySchema) RemoveLabel() *EntitySchema

RemoveLabel allows to remove the 'label' column from the DB, if no label is needed

func (*EntitySchema) SetAllPersonal

func (thisSchema *EntitySchema) SetAllPersonal() *EntitySchema

SetAllPersonal sets the whole entity type as a personal info

func (*EntitySchema) SetInSwaggerForAdmins

func (thisSchema *EntitySchema) SetInSwaggerForAdmins() *EntitySchema

func (*EntitySchema) SetPersonal

func (thisSchema *EntitySchema) SetPersonal(propertyIDs ...EntityPropertyID) *EntitySchema

SetPersonal allows to tag the personal infos

func (*EntitySchema) SetUniqueCombination

func (thisSchema *EntitySchema) SetUniqueCombination(propertyIDs ...EntityPropertyID) *EntitySchema

SetUniqueCombination allows to specify a UNIQUE constraints on several properties

func (*EntitySchema) SetViewOn

func (thisSchema *EntitySchema) SetViewOn(entityKind EntityKind) *EntitySchema

SetViewOn indicates that the associated entities are just 'views' on another entity

func (*EntitySchema) ShowInSwagger

func (thisSchema *EntitySchema) ShowInSwagger() *EntitySchema

func (*EntitySchema) Table

func (thisSchema *EntitySchema) Table(tableName string) *EntitySchema

Table allows to set the table name for entities associated with this schema

func (*EntitySchema) TrackAll

func (thisSchema *EntitySchema) TrackAll() *EntitySchema

TrackAll indicates that we want to know who created, deleted updated last the entities of this kind, and when

func (*EntitySchema) TrackCreationOnly

func (thisSchema *EntitySchema) TrackCreationOnly() *EntitySchema

TrackOnlyCreation indicates that we want to know only who created these entities, and when

type EntityStatus

type EntityStatus int

EntityStatus defines a status for every entity: created, modified, deleted, etc...

const (
	// EntityStatusDELETED : entities with this status should not be used; they should be physically removed after a while
	EntityStatusDELETED EntityStatus = -1

	// EntityStatusCREATED : entities with this status have just been created
	EntityStatusCREATED EntityStatus = 1

	// EntityStatusUPDATED : entities with this status have been modified only once.
	// An entity status > 0 tells how many times an entity has been updated
	EntityStatusUPDATED EntityStatus = 2
)

func (EntityStatus) String

func (thisStatus EntityStatus) String() string

func (EntityStatus) Val

func (thisStatus EntityStatus) Val() int

Val helps implement the IEnum interface

func (EntityStatus) Values

func (thisStatus EntityStatus) Values() map[int]string

Values helps implement the IEnum interface

type Error

type Error interface {
	error
	Cause() Error
	Root() string
}

Error is Vostok's own interface for errors type Error error

func BulkCreateEntitiesWithNoIDs

func BulkCreateEntitiesWithNoIDs(biContext BiContext, entityKind EntityKind, entitiesAsInterface interface{}) (int64, Error)

BulkCreateEntitiesWithNoIDs is used to bulk insert the given entities into the DB, while performing generic operations before / after the insertion; It uses a Business transaction to make sure everything goes fine, or fails altogether The interface{} here stores a pointer to a slice of pointers to the actual entities. Returns the ID (as an int64) of the first inserted entities. BIG WARNING: INSERTING ENTITIES LIKE THIS DOES NOT ALLOW TO HAVE THEIR IDS KNOWN. SO THERE SHOULD NOT BE ANY SUBSEQUENT PROCESS RELYING ON THESE IDS.

func BulkInsertEntities

func BulkInsertEntities(biContext BiContext, compartment *c.BatchCompartment, units []c.IBatchUnit) Error

BulkInsertEntities : bulk inserts the given units, that should be IEntity instances

func CreateEntities1By1

func CreateEntities1By1(biContext BiContext, entityKind EntityKind, entitiesAsInterface interface{}) Error

CreateEntities1By1 is used to insert given entities into the DB, and performing generic operations before / after the insertion; It uses a Business transaction to make sure everything goes fine, or fails altogether The interface{} here stores a pointer to a slice of pointers to actual entities. WARNING: this function allows to have the IDs of the inserted entities known, but if performance is key, and these IDs not important, then it might be better to use BulkCreateEntitiesWithNoIDs.

func CreateEntity

func CreateEntity(biContext BiContext, entity IEntity) Error

CreateEntity is used to insert a given entity into the DB, and performing generic operations before / after the insertion; It uses a Business transaction to make sure everything goes fine, or fails altogether

func CreateEntityAndAllLinks(biContext BiContext, sourceEntity IEntity, isUpdate bool) Error

CreateEntityAndAllLinks is a method to create an entity and all the linked entities that are not persisted yet

func MapEntities

func MapEntities(biContext BiContext, entityKind EntityKind, maxNbEntities int, minStatus EntityStatus, loadingID LoadingID) (map[string]IEntity, Error)

MapEntities does the same as ListEntities, but the entities are returned mapped by their primary reference; This function should not be used when performance is expected.

func NewErr

func NewErr(errorString string, errorParams ...interface{}) Error

NewErr replaces fmt.Errorf; it should help remove all occurrences of Go native function fmt.Errorf mostly to encourage calling NewErrC, which allow to keep a whole chain of error causes

func NewErrC

func NewErrC(cause error, errorString string, errorParams ...interface{}) Error

NewErrC is the same as NewErr except that it can keep track of a cause of error

func ReadEntityLinks(biContext BiContext, minStatus EntityStatus, linksLoadingID LoadingID, entities ...IEntity) Error

ReadEntityLinks loads entity links for given entities, according to a loading plan

func RunPurgeEntities

func RunPurgeEntities(biContext BiContext, params map[string]string, doRun bool) (string, Error)

RunPurgeEntities is the function responsible

func RunSimpleSearch

func RunSimpleSearch(biContext BiContext, simpleSearch ISimpleSearchEntity, loadingID LoadingID) Error

RunSimpleSearch performs a simple search, based on a simple search entity

func SQLGetBool

func SQLGetBool(rawBytes *sql.RawBytes) (bool, Error)

SQLGetBool : mapping SQL -> Go or Vostok type

func SQLGetInt

func SQLGetInt(rawBytes *sql.RawBytes) (int, Error)

SQLGetInt : mapping SQL -> Go or Vostok type

func SQLGetTime

func SQLGetTime(rawBytes *sql.RawBytes) (*time.Time, Error)

SQLGetTime : mapping SQL -> Go or Vostok type

func SQLGetUint64

func SQLGetUint64(rawBytes *sql.RawBytes) (uint64, Error)

SQLGetUint64 : mapping SQL -> Go or Vostok type

func SaveEntities

func SaveEntities(biContext BiContext, entityKind EntityKind, entitiesAsInterface interface{}, loadingBeforeUpdate LoadingID) Error

SaveEntities is used to save given entities into the DB, and performing generic operations before / after the insertion; It uses a Business transaction to make sure everything goes fine, or fails altogether The interface{} here stores a pointer to a slice of pointers to actual entities.

func SaveEntity

func SaveEntity(biContext BiContext, entity IEntity, loadingBeforeUpdate LoadingID) Error

SaveEntity is a method to save an entity, i.e. inserting it if it does not exist in DB yet, or updating it doing this in a transaction

func UpdateEntityWithNewTransaction

func UpdateEntityWithNewTransaction(biContext BiContext, updated IEntity, loadingBeforeUpdate LoadingID) Error

UpdateEntityWithNewTransaction is used to update a given entity in DB, and performing generic operations before / after the update; It uses a Business transaction to make sure everything goes fine, or fails altogether

func UpdateEntityWithinTransaction

func UpdateEntityWithinTransaction(biContext BiContext, updated IEntity, loadingBeforeUpdate LoadingID) Error

UpdateEntityWithinTransaction allows to update a given entity TODO _JW$1: prevent updating an entity that is not completely loaded loadingBeforeUpdate : how we should load the entity to be updated, for comparison purposes

func UpdateInCache

func UpdateInCache(biContext BiContext, entity IEntity) Error

UpdateInCache updates the given entity into the global cache, if this corresponds to the cache policy set for the corresponding entity kind; For now, because we do now want to handle the hassle of precisely determining all the linked entities that should be updated too, we may first flush the cache, then insert the entity into it; <----------------> This is not a problem since globally cached entities mostly corresponds to configuration data, so it does not happen very often, and it's normal in this case to perform this kind of light "restart" of the app by cleaning its global cache; <----------------> Wether or not the global cache is flushed depends on the entity kind, through its GetSharedCachePolicy implementation.

type FieldDifference

type FieldDifference struct {
	Entity                        // is a particular kind of geen entity
	Owner       *EntityDifference `db:"owner_id"        json:"owner"       o*:"the entity difference this field difference is attached to"`
	FieldName   string            `db:"fieldName,60"    json:"fieldName"   o*:"the name of the field this difference is about"`
	ValueBefore string            `db:"valueBefore,255" json:"valueBefore" o*:"the value of a field before a change"`
	ValueAfter  string            `db:"valueAfter,255"  json:"valueAfter"  o*:"the value of a field after a change"`
}

FieldDifference defines the structure of a field difference, i.e. properties & links, plus basic methods

func (*FieldDifference) InitSchema

func (thisFieldDifference *FieldDifference) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type GBatchFunction

type GBatchFunction func(biContext BiContext, compartment *c.BatchCompartment, units []c.IBatchUnit) Error

GBatchFunction defines the signature of a function in Geen that knows what to do of a set of units coming from a given batch compartment

type GeenTest

type GeenTest struct {
	Item     string // the tested item
	Required string // the description of what's expected for the current item
	Failed   bool   // has the test failed ?
	Message  string // a message explaining why the test is not OK
}

GeenTest allows to capture what's going on during a test

func GenericTestAllPersistency

func GenericTestAllPersistency(biContext BiContext, iterations int, cleanAfter bool) (test *GeenTest)

GenericTestAllPersistency generically test creating / reading / updating / deleting for all the entity types, by randomly generating corresponding entity instances. If cleanAfter = true, then all the entities created during the persistency tests à removed from the DB.

type GenericActionType

type GenericActionType int

GenericActionType is used to define the framework's generic actions on entities

const (
	// ActionCREATE : Action used to create a new entity
	ActionCREATE GenericActionType = iota

	// ActionREAD : Action used to read an existing entity
	ActionREAD

	// ActionUPDATE : Action used to update an existing entity
	ActionUPDATE

	// ActionDELETE : Action used to delete an existing entity
	ActionDELETE

	// ActionLIST : Action used to provide a (most of the time limited) list of entities
	ActionLIST

	// ActionSEARCH : Action used to search for entities
	ActionSEARCH

	// ActionFIND : Action used to quick-search for entities
	ActionFIND

	// ActionSAVE : Action used to save an entity, i.e. create or update it
	ActionSAVE

	// ActionLAST : This action is not used as one, but allows specific actions to be defined starting from this one
	ActionLAST
)

func (GenericActionType) GetActionName

func (thisActionType GenericActionType) GetActionName() string

GetActionName returns a label for a given action type (which is coded as an int) This makes a 'GenericActionType' be a 'IActionType'

func (GenericActionType) String

func (thisActionType GenericActionType) String() string

func (GenericActionType) Val

func (thisActionType GenericActionType) Val() int

Val helps implement the IEnum interface

func (GenericActionType) Values

func (thisActionType GenericActionType) Values() map[int]string

Values helps implement the IEnum interface

type Gravity

type Gravity int

Gravity defines an enum allowing to put a gravity level on a message sent within an API call response

const (
	// GravitySUCCESS : for succesfull server operations
	GravitySUCCESS Gravity = 1 - iota

	// GravityINFO : for info messages
	GravityINFO

	// GravityWARNING : for warning messages
	GravityWARNING

	// GravityERROR : for error messages
	GravityERROR
)

func (Gravity) String

func (thisGravity Gravity) String() string

func (Gravity) Val

func (thisGravity Gravity) Val() int

Val helps implement the IEnum interface

func (Gravity) Values

func (thisGravity Gravity) Values() map[int]string

Values helps implement the IEnum interface

type HTTPMethodType

type HTTPMethodType int

HTTPMethodType defines an enum for all the HTTP methods handled by the framework

const (
	// HTTPGET : the GET method
	HTTPGET HTTPMethodType = iota

	// HTTPPOST : the POST method
	HTTPPOST

	// HTTPPUT : the PUT method
	HTTPPUT

	// HTTPDELETE : the DELETE method
	HTTPDELETE

	// HTTPOPTIONS : the OPTIONS method
	HTTPOPTIONS

	// HTTPHEAD : the HEAD method
	HTTPHEAD

	// HTTPPATCH : the PATCH method
	HTTPPATCH
)

func (HTTPMethodType) String

func (thisMethodType HTTPMethodType) String() string

func (HTTPMethodType) Val

func (thisMethodType HTTPMethodType) Val() int

Val helps implement the IEnum interface

func (HTTPMethodType) Values

func (thisMethodType HTTPMethodType) Values() map[int]string

Values helps implement the IEnum interface

type IActionType

type IActionType interface {
	IEnum // an action type is an enum
	GetActionName() string
}

IActionType allows to define actions, like: "create", "update", "read", "delete", "list", etc.

type IAuthorizationBearer

type IAuthorizationBearer interface {
	// GetAllowedOperations returns the slice of the operations  this bearer has access to
	GetAllowedOperations() []*WebOperation
	// AddToAllowedOperations allows to add a WebOperation instance to those already here; it must check that we're not adding the same WebOperation twice
	AddToAllowedOperations(ws *WebOperation)
	// IsOperationAllowed tells if a given web operation is allowed for this bearer
	IsOperationAllowed(ws *WebOperation) bool
}

IAuthorizationBearer allows to manipulate entities that link to web operations, like User and UserGroup

type IBaseScheduler

type IBaseScheduler interface {
	// GetOriginalJobConfig returns a jobConfig instance if it exists
	GetOriginalJobConfig(jobID string, doPanicIfNotFound bool) *c.JobConfig
	// ScheduleFunction puts a named function into the scheduler, with a given schedule, and the function's arguments.
	// This is a low level method that do not use the app server's job configurations.
	ScheduleFunction(name string, schedule string, fn interface{}, args ...interface{}) error
	// RemoveFunction removes a function that has been put into the scheduler
	RemoveFunction(name string)
	// BindOriginalFunction allows to keep in memory that we use a certain name, for a given function
	BindOriginalFunction(name string, jfunc interface{})
}

IBaseScheduler is the type for the scheduler we use in geen

type IEntity

type IEntity interface {

	// InitSchema is used to initialize this Entity's schema
	InitSchema() *EntitySchema
	// GetID returns returns the entity's ID
	GetID() EntityID
	// GetKind returns returns the entity's kind
	GetKind() EntityKind
	// GetLabel returns returns the entity's label
	GetLabel() string
	// GetEntityStatus returns returns this entity's status
	GetEntityStatus() EntityStatus
	// GetCreatedByID : returns the ID of the user that created this entity
	GetCreatedByID() EntityID
	// GetCreatedBy : returns the name of the user that created this entity
	GetCreatedBy() string
	// GetCreation : returns the creation date (Unix time)
	GetCreation() *time.Time
	// GetDeletedByID : returns the ID of the user that deleted this entity
	GetDeletedByID() EntityID
	// GetDeletedBy : returns the name of the user that deleted this entity
	GetDeletedBy() string
	// GetDeletion : returns the deletion date (Unix time)
	GetDeletion() *time.Time
	// GetModifiedByID : returns the ID of the latest user that modified this entity
	GetModifiedByID() EntityID
	// GetModifiedBy : returns the name of the latest user that modified this entity
	GetModifiedBy() string
	// GetModification : returns the latest modification date (Unix time)
	GetModification() *time.Time
	// SetID allows to set the entity's ID
	SetID(ID EntityID)
	// SetKind is implemented here once and for all
	SetKind(kind EntityKind)

	// SetLabel allows to set the entity's label
	SetLabel(label string)
	// SetEntityStatus sets this entity's status
	SetEntityStatus(status EntityStatus)
	// SetCreatedByID : sets the ID of the user that created this entity
	SetCreatedByID(arg EntityID)
	// SetCreatedBy : sets the name of the user that created this entity
	SetCreatedBy(arg string)
	// SetCreation : sets the creation date (Unix time)
	SetCreation(arg *time.Time)
	// SetDeletedByID : sets the ID of the user that deleted this entity
	SetDeletedByID(arg EntityID)
	// SetDeletedBy : sets the name of the user that deleted this entity
	SetDeletedBy(arg string)
	// SetDeletion : sets the deletion date (Unix time)
	SetDeletion(arg *time.Time)
	// SetModifiedByID : sets the ID of the latest user that modified this entity
	SetModifiedByID(arg EntityID)
	// SetModifiedBy : sets the name of the latest user that modified this entity
	SetModifiedBy(arg string)
	// SetModification : sets the latest modification date (Unix time)
	SetModification(arg *time.Time)

	// GetLoadingID : tells us if the entity has been loaded with a particular loading plan, if not empty
	GetLoadingID() LoadingID

	// Equals : tells if this entity is the same as the given one
	Equals(entity IEntity) bool

	// BuildLabel : has to be be used to refresh the entity's label if it depends on other properties, and indicates if a label should be persisted
	BuildLabel() (label string, persisted bool)
	// IsHashed : indicates if the entity is to be hashed before being saved
	IsHashed() bool
	// GetHashSource : provides the string made from some of the entities properties, that is then hashed by the framework
	GetHashSource() string
	// GetSharedCachePolicy allows to indicate, for all the entities of the same kind how to cache them, i.e.
	// - for how long ? A given duration, or one of these values: SharedCacheDurationNEVER, SharedCacheDurationFOREVER, SharedCacheDurationDEFAULT
	// - should a flush be performed before updating the partitioned cache ?
	// The caching of an entity may depend on the use for it, which is linked to how it is loaded,
	// hence the loading ID as an argument here, which is part of the cache key.
	GetSharedCachePolicy(loadingID LoadingID) (duration time.Duration, flushBeforeUpdate bool)
	// IsValid is the method through which an entity checks its own validity
	IsValid(biContext BiContext) Error
	// ChangeBeforeIsExists allows to perform specific treatments on the entity before checking for its existence
	ChangeBeforeIsExists(biContext BiContext) Error
	// ChangeBeforeInsert allows to perform specific treatments on the entity before inserting it
	ChangeBeforeInsert(biContext BiContext) Error
	// ChangeAfterInsert allows to perform specific treatments on the entity after inserting it
	ChangeAfterInsert(biContext BiContext) Error
	// CanBeRead tells us if the given entity can be read (return is nil) or not (return is an error)
	// Whether the entity can be read or not may depend on how it's loaded
	CanBeRead(biContext BiContext, loadingID LoadingID) Error
	// DoAfterRead allows to perform some checks or changes right after reading an entity
	// What is done to the entity after reading it may depend on how it's loaded
	DoAfterRead(biContext BiContext, loadingID LoadingID) Error
	// DoAfterReadLinks allows to perform some checks or changes right after reading an entity's links
	// What happens after reading the entity's links may depend on how it's loaded
	DoAfterReadLinks(biContext BiContext, loadingID LoadingID) Error
	// CanBeUpdated tells us if the given entity can be updated, and if the changes are acceptable or not
	CanBeUpdated(biContext BiContext, instore IEntity) Error
	// ChangeBeforeUpdate allows to perform specific treatments on the entity before updating it
	ChangeBeforeUpdate(biContext BiContext) Error
	// ChangeAfterUpdate allows to perform specific treatments on the entity after updating it
	ChangeAfterUpdate(biContext BiContext) Error
	// ChangeBeforeCaching allows to perform specific treatments on the entity before caching it
	ChangeBeforeCaching(biContext BiContext) Error
	// GetLoadingBeforeUpdate tells how to load the instore version of an entity we're about to update, for controls
	GetLoadingBeforeUpdate() string
	// CanBeDeleted tells us if the given entity can be updated, and if the changes are acceptable or not
	CanBeDeleted(biContext BiContext, instore IEntity) Error
	// IsDiffed indicates if the changes brought through updating the entity should be tracked
	IsDiffed() bool

	// Load : allows to build a loading plan for this entity
	Load(loadingID LoadingID, with ...ILoadingPlan) ILoadingPlan

	// AllLinksOnDepth : builds a loading plan of a given depth
	AllLinksOnDepth(loadingID LoadingID, depth int) ILoadingPlan
	// WithNoLink : returns an empty loading plan, i.e. that loads no link
	WithNoLink(loadingID LoadingID) ILoadingPlan

	// DefineLoadingPlan : build and returns a loading plan for this entity kind and a loading ID
	DefineLoadingPlan(loadingID LoadingID) ILoadingPlan

	// GetSpecificSQLQuery should return a SQL query , for this entity, and the given query ID suffix
	// WARNING : since each query built is cached, it MUST NOT have dynamic parts
	GetSpecificSQLQuery(queryIDSuffix QueryIDSuffix) *SQLQuery

	// ---------------------------------------------------------------------------
	// The methods here belong to the WS (web operations) layer
	// i.e. the code must be implemented in a "entityname_ws.go" file
	// ---------------------------------------------------------------------------
	// FromJSON can transform and control an entity that has just been unmarshalled from JSON
	FromJSON() Error
	// BeforeJSON can arrange an entity that is going to be marshalled in JSON.
	// This arrangement can vary, depending on how the entity has been loaded.
	BeforeJSON(loadingID LoadingID) IEntity
	// GetLoadingIDForGenericAction allows to specify how to load the data, when using a generic action handler, corresponding to the given action type
	// DEPRECATED : not used anymore, the loading ID is to be provided while declaring the use of a generic web operation
	GetLoadingIDForGenericAction(action GenericActionType)

	// ---------------------------------------------------------------------------
	// Deprecated methods
	// ---------------------------------------------------------------------------
	// GetGlobalCacheDuration is DEPRECATED. Replaced by GetSharedCachePolicy.
	GetGlobalCacheDuration(loadingID LoadingID)
	// contains filtered or unexported methods
}

IEntity defines the generic methods that any Entity type should provide

func BuildBareEntityCopy

func BuildBareEntityCopy(entity IEntity) IEntity

BuildBareEntityCopy returns a "bare" version of a given entity, i.e. a copy of the entity with just its fields, no link

func BuildEntityExtract

func BuildEntityExtract(entity IEntity) IEntity

BuildEntityExtract returns an "extract" of an entity, i.e. a copy of an entity with just its kind, ID and label

func BuildLevel1EntityCopy

func BuildLevel1EntityCopy(entity IEntity) IEntity

BuildLevel1EntityCopy returns a copy of the given entity, with bare entity copies in place of all its links, instead of a full data tree; this can help preventing JSON cycling issues for instance; WARNING: this method should not be used whenever performance is required, but only for debugging / debugging purposes.

func CreateOrUpdateIfNeeded

func CreateOrUpdateIfNeeded(biContext BiContext, loaded IEntity, newEntity IEntity) IEntity

CreateOrUpdateIfNeeded : creates the given "new entity", if it did not exist yet, or updates it, if changes have been brought, regarding the existing instance coming from the DB; WARNING: this should not be used outside data initialisation code.

func GetJSONEntity

func GetJSONEntity(entity IEntity, loadingID LoadingID) IEntity

GetJSONEntity applies a JSON policy on a give entity, either to lighten it up, or prevent JSON cycling issues

func NewEntity

func NewEntity(entityKind EntityKind) IEntity

NewEntity instantiates a new entity, given its kind

func NewEntityID

func NewEntityID(entityKind EntityKind, id uint64) IEntity

NewEntityID instantates a new entity, given its kind and an ID

func NewRandomEntity

func NewRandomEntity(source rand.Source, entityKind EntityKind, nbLayers int, params RandGenParams) IEntity

NewRandomEntity returns an entity of the given kind with its fields' values randomly generated, and also its links randomly generated, if nbLayers > 0 If nbLayers = 1, then links are generated, if nbLayers = 2, links, and their links, are If OnlyPersisted = true, then only persisted fields are filled If WithID = true, then the ID of the entity and its linked entities is randomly generated If MakeInsertable = true, then the required links is filled, even though withLinks = false If linkBackRefs = true, then all the target entities also link the source entities through the back ref links NB: for now, the random link generation is not implemented

func RandomizeEntity

func RandomizeEntity(source rand.Source, sourceEntity IEntity, nbLayers int, params RandGenParams) IEntity

RandomizeEntity sets random values in the given entity's properties

func RemoveTechnicalProperties

func RemoveTechnicalProperties(entity IEntity) IEntity

func SaveIfNeeded

func SaveIfNeeded(biContext BiContext, newEntity IEntity, loadingID LoadingID) IEntity

SaveIfNeeded : looks at a given new entity, tries to load a version of it with a given loading plan, then creates or updates it if needed

type IEntityProperty

type IEntityProperty interface {
	// GetName returns the name of the property
	GetName() string
	// GetColumnName is the name of the column in which the property is persisted, if it's persisted directly on the entity
	GetColumnName() string

	// IsLink tells us if this property is a link; if not, it's a field
	IsLink() bool
	// IsRequiredInDB tells us if this property is required in DB, i.e. a value must be given
	IsRequiredInDB() bool
	// IsImmutable tells us if this property is immutable, i.e. cannot be changed once set
	IsImmutable() bool
	// IsPureTechnicalProperty tells us if this property is purely technical, i.e. a technical property that cannot really be used for identification
	IsPureTechnicalProperty() bool
	// GetValue retrieves the value associated with a given entity property,
	// from a source entity, given as a Value (through reflect.ValueOf().Elem())
	GetValue(sourceEntityAsElemValue reflect.Value) reflect.Value
	// GetStringValue retrieves the value associated with a given entity link,
	// from a source entity, given as a string
	GetStringValue(sourceEntityAsElemValue reflect.Value) string
	// SetValue allows to change a link's value for an entity given as a value
	SetValue(sourceEntityAsElemValue reflect.Value, valueToSet reflect.Value)
	// SetStringValue allows to change a property's value, thanks to a value given as a string
	SetStringValue(sourceEntityAsElemValue reflect.Value, valueAsString string) Error
	// GetSQLValue returns, for a given entity, the property's value as suitable for a SQL column
	GetSQLValue(sourceEntityAsElemValue reflect.Value) interface{}
	// GetMaskedSQLValue returns, for a given entity, the property's value as suitable for a SQL column,
	// if is not confidential; if it is, then the value is obfuscated; this serves for debbugging, logging purposes
	GetMaskedSQLValue(sourceEntityAsElemValue reflect.Value) interface{}
	// IsZeroValue tells if the value associated with the given property is the zero value
	IsZeroValue(sourceEntityAsElemValue reflect.Value) bool
	// IsConfidential : if true then the property should be fetched from the DB with extra care
	IsConfidential() bool
	// SetConfidential : sets the confidential mode
	SetConfidential() IEntityProperty
	// IsInputProperty : can this property be expected as a user input ?
	IsInputProperty() bool
	// IsMandatoryInput : must the user fill this property ?
	IsMandatoryInput() bool
	// contains filtered or unexported methods
}

IEntityProperty defines common methods for entity properties, whereas they are links or fields

type IEnum

type IEnum interface {
	fmt.Stringer // each enum value has a label
	Val() int
	Values() map[int]string
}

IEnum helps define enums

type IGeenConfig

type IGeenConfig interface {
	GetMaxListSize() int
	GetUsers() []IUser
	IsTestSchemasAtLaunch() bool
	GetExampleFilePath() string
}

IGeenConfig is the interface that the custom part of a config should implement in a geen-based application

type ILoadingPlan

type ILoadingPlan interface {
	fmt.Stringer
	// GetAssociatedKind : the entity kind associated with this loading plan
	GetAssociatedKind() EntityKind

	// GetChildren : the loading plans that have this loading plan as a parent, representing the sub-links to load
	GetChildren() map[EntityPropertyID]ILoadingPlan

	// OneWay : sets the OneWay mode, cf. isOneWay() for signification.
	// If propagate = true, then this is also applied to the sub-loading plans
	OneWay(propagate bool) ILoadingPlan

	// NoTechnical : sets this loading plan to the "without technical data" mode; cf. isNoTechnical()
	// If propagate = true, then this is also applied to the sub-loading plans
	NoTechnical(propagate bool) ILoadingPlan

	// FieldsOnly : sets this loading plan to the "only fields" mode; cf. isFieldsOnly()
	// If propagate = true, then this is also applied to the sub-loading plans
	FieldsOnly(propagate bool) ILoadingPlan

	// AllowConfidential : allows the confidential data to be loaded
	// If propagate = true, then this is also applied to the sub-loading plans
	AllowConfidential(propagate bool) ILoadingPlan
	// contains filtered or unexported methods
}

ILoadingPlan is used to define which public operations a loading plan should expose

func With

func With(linkID EntityPropertyID, with ...ILoadingPlan) ILoadingPlan

With allows to define a sub-loading plan

type ILogger

type ILogger interface {
	IsVerbose() bool  // tells if we're in verbose mode; a logger can tell since it has to know to chose what to log
	core.LoggingScope // now we want that all the logging to be done within a LoggingScope
}

ILogger defines an interface for an object able to log at the dev level

type IOperationResponse

type IOperationResponse interface {
	GetMessages() []Message
	GetStatus() int
}

IOperationResponse is the type of the functions that handle all the web operations

type ISimpleSearchEntity

type ISimpleSearchEntity interface {
	IEntity
	// GetResultLinkID returns the ID of the link associated with the search results - MUST be a multiple link
	GetResultLinkID() EntityPropertyID
	// InitAllCriteria allows to list all the fields / links that can be used as criteria; and also the list of results MUST be initialised
	InitAllCriteria()
	// AppendResult is the method through which an entity found by the search is added to the search results
	AppendResult(result IEntity)
	// GetDescription returns a readable description of what this search is about
	GetDescription() string
	// GetValuedCriteria returns a list of the criteria that will effectively be of use in a search
	GetValuedCriteria() []*SimpleSearchCriterion

	// GetSignature returs a "binary" (ex. "01011") signature for the list of criteria
	GetSignature() string

	// GetOrderBy returns the ID of the property which should be used to order the results; if "", then no sorting is done
	GetOrderBy() (EntityPropertyID, OrderType)
	// GetDefaultMaxResults returns the default max number of entities returned; if <= 0: no limit
	GetDefaultMaxResults() int
	// GetMaxResults returns the max number of entities returned; if <= 0: no limit
	GetMaxResults() int
	// GetMinStatus returns the mininam status for the entities to be retrieved by the search
	GetMinStatus() EntityStatus
	// contains filtered or unexported methods
}

ISimpleSearchEntity defines what a list of criteria should look like

type IUser

type IUser interface {
	IEntity // a user is a particular kind of entity
	GetUsername() string
	GetPassword() string
	IsPhysical() bool
	IsAdmin() bool
	IsSuperUser() bool
	IsActive() bool
}

IUser defines the operations provided by user instances

func GetTestUser

func GetTestUser() IUser

GetTestUser returns a user, that we use for tests

type IWithName

type IWithName interface {
	GetName() string
}

IWithName helps recognize entities that bear a name

type IWithNameAndDescription

type IWithNameAndDescription interface {
	IWithName
	GetDescription() string
}

IWithNameAndDescription helps recognize entities that bear a name and a description

type Job

type Job struct {
	Entity                         // is a particular kind of geen entity
	JobConfig    *JobConfiguration `db:"jobConfig_id"   json:"jobConfig,omitempty"    o*:"the configuration for this job"`
	UID          string            `db:"uid,32"         json:"uid,omitempty"          o*:"the job ID"`
	Schedule     string            `db:"schedule,32"    json:"schedule,omitempty"     o*:"the job schedule, as a cron task, example: '* * * * *'"`
	Started      *time.Time        `db:"started,0"      json:"started,omitempty"      o*:"when the job was started, if it has been started"`
	Finished     *time.Time        `db:"finished,0"     json:"finished,omitempty"     o*:"when the job has finished, if it has"`
	Duration     int64             `db:"duration"       json:"duration,omitempty"     o*:"the job duration, in milliseconds"`
	Status       jobStatus         `db:"status,1"       json:"status,omitempty"       o*:"the job status"`
	StatusString string            `db:"-"              json:"statusString,omitempty" o*:"the job status (as a string)"`
	Comment      string            `db:"comment,255"    json:"comment,omitempty"      o*:"a comment, as additional info to the status"`
	WorkerID     int               `db:"workerID"       json:"workerID,omitempty"     o*:"the ID of the worker running this job"`
	WorkerUses   int               `db:"workerUses"     json:"workerUses,omitempty"   o*:"the number of jobs run by the worker so far"`
}

Job defines the structure of a ????, i.e. properties & links, plus basic methods

func NewJob

func NewJob() *Job

NewJob is a shortcut to instantiate a new Job

func (*Job) BeforeJSON

func (thisJob *Job) BeforeJSON(loadingID LoadingID) IEntity

BeforeJSON can arrange an entity that is going to be marshalled in JSON

func (*Job) InitSchema

func (thisJob *Job) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type JobConfiguration

type JobConfiguration struct {
	Entity                  // is a particular kind of geen entity
	UID         string      `db:"uid,32"          json:"uid,omitempty"         i*:"the job ID"`
	Description string      `db:"description,255" json:"description,omitempty" i*:"the job description"`
	Schedule    string      `db:"schedule,32"     json:"schedule,omitempty"    i*:"the job schedule"`
	Active      bool        `` /* 144-byte string literal not displayed */
	Params      []*JobParam `db:"-"               json:"params,omitempty"      in:"the job params"`
	PastJobs    []*Job      `db:"-"               json:"pastJobs,omitempty"    o*:"the jobs that have run with this config"`
	// contains filtered or unexported fields
}

JobConfiguration defines the structure of a Job Configuration, i.e. properties & links, plus basic methods. This is different from vostok.JobConfig since the parameters here are also entities, not just key-value pairs.

func NewJobConfiguration

func NewJobConfiguration() *JobConfiguration

NewJobConfiguration is a shortcut to instantiate a new JobConfiguration

func (*JobConfiguration) ChangeAfterUpdate

func (thisConf *JobConfiguration) ChangeAfterUpdate(biContext BiContext) Error

ChangeAfterUpdate allows to perform specific treatments on the entity after updating it

func (*JobConfiguration) DefineLoadingPlan

func (thisConf *JobConfiguration) DefineLoadingPlan(loadingID LoadingID) ILoadingPlan

DefineLoadingPlan : build and returns a loading plan for this entity kind and a loading ID

func (thisConf *JobConfiguration) DoAfterReadLinks(biContext BiContext, loadingID LoadingID) Error

DoAfterReadLinks allows to perform some checks or change right after reading an entity's links What happens after reading the entity's links may depend on how it's loaded

func (*JobConfiguration) GetSharedCachePolicy

func (thisConf *JobConfiguration) GetSharedCachePolicy(loadingID LoadingID) (duration time.Duration, flushBeforeUpdate bool)

GetSharedCachePolicy allows to indicate, for all the entities of the same kind how to cache them, i.e. - in a shared cache common to this entity kind, or the global cache, - for how long ? A given duration, or one of these values: SharedCacheDurationNEVER, SharedCacheDurationFOREVER, SharedCacheDurationDEFAULT - should a flush be performed before updating the partitioned cache ?

func (*JobConfiguration) InitSchema

func (thisConf *JobConfiguration) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type JobParam

type JobParam struct {
	Entity                        // is a particular kind of geen entity
	JobConfig   *JobConfiguration `db:"jobConfig_id"   json:"jobConfig,omitempty"   i*:"the job config this parameter belongs to"`
	Name        string            `db:"name,32"        json:"name,omitempty"        i*:"the parameter key"`
	StringValue string            `db:"stringValue,64" json:"stringValue,omitempty" i*:"the parameter string value"`
}

JobParam defines the structure of a ????, i.e. properties & links, plus basic methods

func NewJobParam

func NewJobParam() *JobParam

NewJobParam is a shortcut to instantiate a new JobParam

func (*JobParam) InitSchema

func (thisJobParam *JobParam) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type JobSearch

type JobSearch struct {
	SimpleSearchEntity        // is a particular kind of SEARCH entity
	JobUID             string `db:"-"  json:"jobUID" in:"the UID of the job of which to find the occurrences"`
	Jobs               []*Job `db:"-"  json:"jobs"   o*:"the jobs found through this search"`
}

JobSearch defines the structure of a ????, i.e. properties & links, plus basic methods

func NewJobSearch

func NewJobSearch() *JobSearch

NewJobSearch is a shortcut to instantiate a new JobSearch

func (*JobSearch) AppendResult

func (thisJobSearch *JobSearch) AppendResult(result IEntity)

AppendResult is the method through which an entity found by the search is added to the search results

func (*JobSearch) GetOrderBy

func (thisJobSearch *JobSearch) GetOrderBy() (EntityPropertyID, OrderType)

GetOrderBy returns the ID of the property which should be used to order the results; if "", then no sorting is done

func (*JobSearch) GetResultLinkID

func (thisJobSearch *JobSearch) GetResultLinkID() EntityPropertyID

GetResultLinkID : implementing ISimpleSearchEntity

func (*JobSearch) InitAllCriteria

func (thisJobSearch *JobSearch) InitAllCriteria()

InitAllCriteria : implementing ISimpleSearchEntity

func (*JobSearch) InitSchema

func (thisJobSearch *JobSearch) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type LinkDifference

type LinkDifference struct {
	Entity                                      // is a particular kind of geen entity
	Owner                   *EntityDifference   `db:"owner_id"    json:"owner"    o*:"the entity difference this field difference is attached to"`
	LinkName                string              `db:"linkName,60" json:"linkName" o*:"the value of a field before a change"`
	Added                   EntityFullReference `db:"added,224"   json:"added"    o*:"the reference of a newly associated entity through this link"`
	Removed                 EntityFullReference `db:"removed,224" json:"removed"  o*:"the reference of the entity de-associated through this link"`
	InDepthFieldDifferences []*FieldDifference  `db:"-"           json:"-"        o*:"the field differences found inside 2 versions of the same associated entity"`
	InDepthLinkDifferences  []*LinkDifference   `db:"-"           json:"-"        o*:"the link differences found inside 2 versions of the same associated entity"`
}

LinkDifference defines the structure of a ????, i.e. properties & links, plus basic methods

func NewLinkDifference

func NewLinkDifference(owner *EntityDifference, link *EntityLink, added EntityFullReference, removed EntityFullReference) *LinkDifference

NewLinkDifference is a "constructor"

func (*LinkDifference) InitSchema

func (thisLinkDifference *LinkDifference) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

func (*LinkDifference) WithNum

func (thisLinkDiff *LinkDifference) WithNum(nbDiffsSoFar int) *LinkDifference

WithNum : can be used to refresh the entity's label if it depends on other properties

type LoadingID

type LoadingID string

LoadingID is a string to identify a loading plan, for a given entity kind; For a given entity kind, it should be unique

const (
	// LoadingNOLINK is a generic loading ID for the empty loading plans
	LoadingNOLINK LoadingID = "with_no_link"

	// LoadingFIRSTLAYER is a generic loading ID that can be used to load the first layer of links
	LoadingFIRSTLAYER LoadingID = "first_layer"
)
const LoadingCURRENTUSER LoadingID = "current"

LoadingCURRENTUSER allows to identify the kind of loading we use for the current user

const (
	LoadingENTITYDIFFFORVIEW LoadingID = "diffs_view"
)

Loading IDs

const (
	LoadingJOBCONFIGWITHPARAMS LoadingID = "with_params"
)

Loading IDs

const LoadingUSERINIT LoadingID = "user_init"

LoadingUSERINIT is the loading method used for initialising users in the DB

type Message

type Message struct {
	Title         string  `json:"title"`         // the message title
	Gravity       Gravity `json:"gravity"`       // the message Gravity
	GravityString string  `json:"gravityString"` // the message Gravity (string form)
	Content       string  `json:"content"`       // the message content
}

Message allows to put messages in rest responses

type Operand

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

Operand help us defines where clause operations

func NewOperand

func NewOperand(sqlExpression string, label string) *Operand

NewOperand to create a new operand

type OperationPluralResponse

type OperationPluralResponse struct {
	BaseResponse
	Entities   interface{} `json:"entities"`
	NbEntities int         `json:"nbEntities"`
}

OperationPluralResponse must be used for PLURAL-type response, i.e. when the body should contain several entities

func GenericListHandler

func GenericListHandler(wsContext WsContext, loadingID LoadingID) *OperationPluralResponse

GenericListHandler returns the 100 first instances for the current entity kind

func GenericSaveHandler

func GenericSaveHandler(wsContext WsContext, loadingID LoadingID) *OperationPluralResponse

GenericSaveHandler allows to simply update an entity passed as a JSON object

func GenericSearchHandler

func GenericSearchHandler(wsContext WsContext, loadingID LoadingID) *OperationPluralResponse

GenericSearchHandler returns results from a simple search, i.e. a search performed with a simple search entity containing criteria about the entity fields of the targeted entities

func PluralResponse

func PluralResponse(wsContext WsContext, entitiesAsInterface interface{}, status int, loadingID LoadingID) *OperationPluralResponse

PluralResponse initialises a *OperationPluralResponse with a given set of entities

func (*OperationPluralResponse) ConcatErrors

func (thisResponse *OperationPluralResponse) ConcatErrors(title string, errors ...Error) *OperationPluralResponse

ConcatErrors allows to pass several errors to be concatenated in a single message

func (*OperationPluralResponse) Message

func (thisResponse *OperationPluralResponse) Message(gravity Gravity, title string, contentFmt string, contentParams ...interface{}) *OperationPluralResponse

Message allows to add a message to a *OperationPluralResponse

type OperationSingleResponse

type OperationSingleResponse struct {
	BaseResponse
	Entity   IEntity `json:"entity"`
	NoIndent bool    `json:"-"`
}

OperationSingleResponse must be used for SINGLE-type response, i.e. when the body should contain at most 1 entity

func GenericCreateHandler

func GenericCreateHandler(wsContext WsContext, loadingID LoadingID) *OperationSingleResponse

GenericCreateHandler allows to simply create an entity passed as a JSON object

func GenericDeleteHandler

func GenericDeleteHandler(wsContext WsContext, loadingID LoadingID) *OperationSingleResponse

GenericDeleteHandler allows to delete an entity, given its primary reference (which can be its ID)

func GenericReadHandler

func GenericReadHandler(wsContext WsContext, loadingID LoadingID) *OperationSingleResponse

GenericReadHandler allows to simply read an entity, given its primary reference (which can be its ID)

func GenericUpdateHandler

func GenericUpdateHandler(wsContext WsContext, loadingID LoadingID) *OperationSingleResponse

GenericUpdateHandler allows to simply update an entity passed as a JSON object

func SingleResponse

func SingleResponse(wsContext WsContext, entity IEntity, status int, loadingID LoadingID) *OperationSingleResponse

SingleResponse initialises a *OperationSingleResponse with a given entity. An http status must be provided, and the loading ID of the entity should be passed, since the preparation before the JSON marshalling depends on it.

func (*OperationSingleResponse) ConcatErrors

func (thisResponse *OperationSingleResponse) ConcatErrors(title string, errors ...Error) *OperationSingleResponse

ConcatErrors allows to pass several errors to be concatenated in a single message

func (*OperationSingleResponse) Message

func (thisResponse *OperationSingleResponse) Message(gravity Gravity, title string, contentFmt string, contentParams ...interface{}) *OperationSingleResponse

Message allows to add a message to a *OperationSingleResponse

type OrderType

type OrderType string

OrderType tells if we sort by ASC ou DESC order

const (
	OrderTypeASC  OrderType = "ASC"
	OrderTypeDESC OrderType = "DESC"
)

We define the order types here

type PluralResponseFunction

type PluralResponseFunction func(wsContext WsContext, loadingID LoadingID) *OperationPluralResponse

PluralResponseFunction is the kind of operation function that returns a OperationPluralResponse

type PropertyType

type PropertyType int

PropertyType represents the type of an entity's property

const (
	// PropertyTypeUNKNOWN : when the property type is not recognized
	PropertyTypeUNKNOWN PropertyType = iota - 1

	// PropertyTypeBOOL : for boolean properties
	PropertyTypeBOOL

	// PropertyTypeSTRING : for string properties
	PropertyTypeSTRING

	// PropertyTypeURL : for URL string properties
	PropertyTypeURL

	// PropertyTypeEMAIL : for email properties
	PropertyTypeEMAIL

	// PropertyTypeENTITYID : for entity IDs
	PropertyTypeENTITYID

	// PropertyTypeENTITYREFERENCE : for entity references
	PropertyTypeENTITYREFERENCE

	// PropertyTypeINT : for integer properties
	PropertyTypeINT

	// PropertyTypeREAL32 : for 32-bits real number properties
	PropertyTypeREAL32

	// PropertyTypeREAL64 : for 64-bits real number properties
	PropertyTypeREAL64

	// PropertyTypeAMOUNT : for amount of money (which is a float64)
	PropertyTypeAMOUNT

	// PropertyTypeDATE : for date properties
	PropertyTypeDATE

	// PropertyTypeENUM : for enum properties
	PropertyTypeENUM

	// PropertyTypeLINK : for links to other entities
	PropertyTypeLINK

	// PropertyTypeJSON : for JSON strings
	PropertyTypeJSON
)

func (PropertyType) String

func (thisProperty PropertyType) String() string

func (PropertyType) Val

func (thisProperty PropertyType) Val() int

Val helps implement the IEnum interface

func (PropertyType) Values

func (thisProperty PropertyType) Values() map[int]string

Values helps implement the IEnum interface

type QueryExecContext

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

QueryExecContext wraps a query as well as the values to be used to fill this query, and maybe a debug string, to help check the query execution in the logs

func (*QueryExecContext) DebugWith

func (queryCtx *QueryExecContext) DebugWith(debugValues ...interface{}) *QueryExecContext

DebugWith helps create a context from a query, with values passed to fill it before execution

func (*QueryExecContext) GetDebugQuery

func (queryCtx *QueryExecContext) GetDebugQuery(withValues bool) string

GetDebugQuery returns, depending on the log mode, a string of the given SQL query, and, if the mode is verbose, with the params replacing the '?'. Some values passed here may be masked for confidentiality.

type QueryID

type QueryID string

QueryID allows use to uniquely identify each request

type QueryIDSuffix

type QueryIDSuffix string

QueryIDSuffix is a type of string that is used to build a Query ID

const (
	QueryIDSuffixEXISTS        QueryIDSuffix = "_exists"
	QueryIDSuffixINSERT        QueryIDSuffix = "_insert"
	QueryIDSuffixINSERTLINK    QueryIDSuffix = "_insert_link"
	QueryIDSuffixREMOVELINK    QueryIDSuffix = "_remove_link"
	QueryIDSuffixUPDATE        QueryIDSuffix = "_update"
	QueryIDSuffixSELECT        QueryIDSuffix = "_select"
	QueryIDSuffixSELECTREF     QueryIDSuffix = "_select_ref"
	QueryIDSuffixSELECTLINK    QueryIDSuffix = "_select_link"
	QueryIDSuffixSIMPLESEARCH  QueryIDSuffix = "_simple_search"
	QueryIDSuffixLIST          QueryIDSuffix = "_list"
	QueryIDSuffixQUICKSEARCH   QueryIDSuffix = "_quick_search"
	QueryIDSuffixDYNAMICCOUNT  QueryIDSuffix = "_dyn_count"
	QueryIDSuffixDYNAMICDELETE QueryIDSuffix = "_dyn_delete"
	QueryIDSuffixDYNAMICSELECT QueryIDSuffix = "_dyn_select"
	QueryIDSuffixREMOVE        QueryIDSuffix = "_remove"
	QueryIDSuffixBULKINSERT    QueryIDSuffix = "_bulk_insert"
)

We define here some generic query ID suffices

type RandGenParams

type RandGenParams struct {
	OnlyPersisted  bool // to generate only the properties that are persisted
	WithID         bool // to generate an ID, instead of having it generated by the DB
	MakeInsertable bool // forces the generation of entities in required links, even if no linked entity should be generated at first
	LinkBackRefs   bool // performs the backward entity linking
	Regenerate     bool // if true, then it means we're regenerating an existing entity, to simulate user changes
	NoKind         bool // if true, then the entity kind is removed
	NoLabel        bool // if true, then the entity label is removed
}

RandGenParams gathers some of the parameters involved in random entity generation

type Resource

type Resource struct {
	Entity                                     // a Resource is a particular kind of entity
	ResourceKind    EntityKind                 `json:"resourceKind"         o*:"the entity kind this resource is associated with"`
	Group           functionalGroup            `json:"group"                o*:"the group - i.e. - functionality package, this resource belongs to"`
	EntitySchemaURL core.URL                   `json:"entitySchemaURL"      o*:"path to the schema for the entities associated with this resource"`
	Operations      []*WebOperation            `json:"operations,omitempty" o*:"the operations associated with an entity kind"`
	OperationNames  map[string]protectionLabel `json:"operationNames"       o*:"a map containing the names of the operations  attached to the resource"`
}

Resource defines the structure of a resource, i.e. the set of web operations associated to an entity kind The role of a 'Resource' is to describe the structure of the associated entity kind, i.e. the set of fields, the type of each of them, various constraints on them, etc.

func (*Resource) InitSchema

func (thisResource *Resource) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity kind

func (*Resource) IsVisible

func (thisResource *Resource) IsVisible(appContext AppContext) bool

IsVisible tells is the given user can access this operation

type RoutineBiContext

type RoutineBiContext interface {
	BiContext // a Routine Context has to offer the same operations  as any BI Context
	Release() // Release frees the inner Routine back into the routine pool
}

RoutineBiContext is an interface for a routine that can be used as a BI Context, and can also be released once the go routine job is finished.

Typical use case is: routineCtx := mainBiContext.NewRoutineBiContext() defer routineCtx.Release() routineCtx.Log().Infof( "Starting doing stuff from this context")

type RoutineContextOrigin

type RoutineContextOrigin interface {
	BiContext // it is a full-fledge BI Context
	DbOwner   // but also a DB owner
}

RoutineGenerator is the type for the object in Geen that can create a RoutineBiContext

type SQLDynamicQuery

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

SQLDynamicQuery is an extension of SQLQuery that adds methods for the dynamic aspects

func Count

func Count(kind EntityKind) *SQLDynamicQuery

Count builds a dynamic SELECT COUNT query

func Select

func Select(kind EntityKind, minStatus EntityStatus, loadingID LoadingID) *SQLDynamicQuery

Count builds a dynamic SELECT query

func (*SQLDynamicQuery) AsEntities

func (dynQuery *SQLDynamicQuery) AsEntities(biContext BiContext) ([]IEntity, Error)

AsEntities actually runs the query, and returns the entities found in the list

func (*SQLDynamicQuery) AsInt

func (dynQuery *SQLDynamicQuery) AsInt(biContext BiContext) (int, Error)

AsInt actually runs the query, and returns the unique result of the execution of the dynamic query as an int

func (*SQLDynamicQuery) AsString

func (dynQuery *SQLDynamicQuery) AsString(biContext BiContext) (string, Error)

AsString actually runs the query, and returns the unique result of the execution of the dynamic query as a string

func (*SQLDynamicQuery) NbRows

func (dynQuery *SQLDynamicQuery) NbRows(biContext BiContext) (int64, Error)

NbRows actually runs the query, and returns the number of rows affected by the execution of the dynamic query

func (*SQLDynamicQuery) Where

func (dynQuery *SQLDynamicQuery) Where(criterion string, value interface{}) *SQLDynamicQuery

Where allows to add a new criterion to the query; e.g. Where("EntityStatus>", -2), Where("Name=", "Dupond")

func (*SQLDynamicQuery) WhereAll

func (dynQuery *SQLDynamicQuery) WhereAll(criterionValuePairs map[string]interface{}) *SQLDynamicQuery

WhereAll allows to add several pairs of criterion / value at once

type SQLQuery

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

SQLQuery is our own type for SQL queries. It shall allow us to better control how we manipulate SQL queries, and how to build tools around that. For now, it's just a string, but that should evolve.

func GetSQLQuery

func GetSQLQuery(dbContext DbContext, entityKind EntityKind, queryIDSuffix QueryIDSuffix) *SQLQuery

GetSQLQuery returns a SQL query as a string, for a given entity kind, and a given QueryIDSuffix

func GetSQLQueryWithConfig

func GetSQLQueryWithConfig(dbContext DbContext, entityKind EntityKind, queryIDSuffix QueryIDSuffix, queryConfiguration *queryConfiguration) *SQLQuery

GetSQLQueryWithConfig returns a SQL query as a string, for a given entity kind, and a given QueryIDSuffix It can take an additionnal object, like an entity link, or a search entity

func SQLQueryf

func SQLQueryf(entityKind EntityKind, queryIDSuffix QueryIDSuffix, qConfig *queryConfiguration, formatStringQuery string, formatStringArgs ...interface{}) *SQLQuery

SQLQueryf builds a SQLQuery from a format string and format arguments

func (*SQLQuery) GetString

func (sqlQuery *SQLQuery) GetString() string

GetString returns the string version of the given query

func (*SQLQuery) SetIsRead

func (sqlQuery *SQLQuery) SetIsRead() *SQLQuery

SetIsRead allows to indicate that a query is of READ type (i.e. not a query for writing stuff)

func (*SQLQuery) ToContext

func (sqlQuery *SQLQuery) ToContext() *QueryExecContext

ToContext helps create a context from a query, when no value are needed to fill it before execution

func (*SQLQuery) With

func (sqlQuery *SQLQuery) With(values ...interface{}) *QueryExecContext

With helps create a context from a query, with values passed to fill it before execution

type SimpleSearchCriterion

type SimpleSearchCriterion struct {
	SearchedEntityFieldProperty EntityPropertyID
	SearchedEntityLinkProperty  EntityPropertyID
	Operand                     *Operand
	SearchObjectValueField      EntityPropertyID
}

SimpleSearchCriterion defines what a simple search criterion should look like

func NewFieldCriterion

func NewFieldCriterion(searchedEntityLinkProperty EntityPropertyID, operand *Operand, searchObjectValueField EntityPropertyID) *SimpleSearchCriterion

NewFieldCriterion builds a new criterion based on a field of the entity type that is searched in DB

func NewLinkCriterion

func NewLinkCriterion(searchedEntityLinkProperty EntityPropertyID, operand *Operand, searchObjectValueField EntityPropertyID) *SimpleSearchCriterion

NewLinkCriterion builds a new criterion based on a link of the entity type that is searched in DB

type SimpleSearchEntity

type SimpleSearchEntity struct {
	Entity                  // is a particular kind of geen entity
	Signature  string       `` /* 164-byte string literal not displayed */
	MinStatus  EntityStatus `json:"minStatus,omitempty"  in:"the entity status from which to consider the entities to be found"`
	MaxResults int          `json:"maxResults,omitempty" in:"the max number of entities returned"`
	NbResults  int          `json:"nbResults,omitempty"  o*:"the number of results found; if absent, this is equivalent to 0"`
	// contains filtered or unexported fields
}

SimpleSearchEntity defines the structure of a ????, i.e. properties & links, plus basic methods

func NewSimpleSearch

func NewSimpleSearch(kind EntityKind) SimpleSearchEntity

NewSimpleSearch helps us instantiate a new simple search entity

func (*SimpleSearchEntity) GetDefaultMaxResults

func (thisSearch *SimpleSearchEntity) GetDefaultMaxResults() int

GetDefaultMaxResults returns the default max number of entities returned; if <= 0: no limit

func (*SimpleSearchEntity) GetDescription

func (thisSearch *SimpleSearchEntity) GetDescription() string

GetDescription : implementing ISimpleSearchEntity

func (*SimpleSearchEntity) GetMaxResults

func (thisSearch *SimpleSearchEntity) GetMaxResults() int

GetMaxResults returns the max number of entities returned; if <= 0: no limit

func (*SimpleSearchEntity) GetMinStatus

func (thisSearch *SimpleSearchEntity) GetMinStatus() EntityStatus

GetMinStatus returns the mininam status for the entities to be retrieved by the search

func (*SimpleSearchEntity) GetOrderBy

func (thisSearch *SimpleSearchEntity) GetOrderBy() (EntityPropertyID, OrderType)

GetOrderBy returns the ID of the property which should be used to order the results; if "", then no sorting is done

func (*SimpleSearchEntity) GetSignature

func (thisSearch *SimpleSearchEntity) GetSignature() string

GetSignature returs a "binary" (ex. "01011") signature for the list of criteria

func (*SimpleSearchEntity) GetValuedCriteria

func (thisSearch *SimpleSearchEntity) GetValuedCriteria() []*SimpleSearchCriterion

GetValuedCriteria returns a list of the criteria that will effectively be of use in a search

func (*SimpleSearchEntity) InitSchema

func (thisSearch *SimpleSearchEntity) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type SingleResponseFunction

type SingleResponseFunction func(wsContext WsContext, loadingID LoadingID) *OperationSingleResponse

SingleResponseFunction is the kind of operation function that returns a OperationSingleResponse

type SwaggerDoc

type SwaggerDoc struct {
	Entity      // is a particular kind of geen entity, so that we can easily handle it through a rest web operation
	oas.Swagger // .. but also a Swagger struct, that can contain all the needed info for a Swagger documentation of an app's API
	// contains filtered or unexported fields
}

SwaggerDoc defines the structure of a ????, i.e. properties & links, plus basic methods

func NewSwaggerDoc

func NewSwaggerDoc() *SwaggerDoc

NewSwaggerDoc is a shortcut to instantiate a new SwaggerDoc

func (*SwaggerDoc) InitSchema

func (thisDoc *SwaggerDoc) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type WSQueryParam

type WSQueryParam struct {
	Entity                   // is a particular kind of geen entity
	Name        string       `json:"name"        o*:"the query parameter's name"`
	Mandatory   bool         `json:"mandatory"   o*:"if true, then this parameter is expected"`
	Description string       `json:"description" o*:"the parameter's description"`
	ParamType   PropertyType `json:"paramType"   o*:"the parameter's type"`
}

WSQueryParam defines the structure of a web operation query param, i.e. properties & links, plus basic methods

func NewWSQueryParam

func NewWSQueryParam(name string, mandatory bool, description string, paramType PropertyType) *WSQueryParam

NewWSQueryParam is a shortcut to instantiate a new WSQueryParam

func (*WSQueryParam) InitSchema

func (thisWSQueryParam *WSQueryParam) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type WebOperation

type WebOperation struct {
	Entity                                       // a Resource is a particular kind of entity
	Name                 string                  `json:"name"                  o*:"the name of a operation has this form: 'action-resourceName'"`
	Action               string                  `json:"action"                o*:"the label for the associated action type"`
	ActionType           IActionType             `json:"-"                     o*:"the action called (read ? delete ? create ? list ? etc.)"`
	LongDescription      string                  `json:"longDescription"       o*:"further details about the operation"`
	ProvideOneFunc       SingleResponseFunction  `json:"-"                     o*:"the function that is responsible for the retrieval of 1 entity"`
	ProvideManyFunc      PluralResponseFunction  `json:"-"                     o*:"the function that is responsible for the retrieval of a set of entities"`
	FirstParamLabel      string                  `` /* 134-byte string literal not displayed */
	FirstParamOptional   bool                    `json:"firstParamOptional"    o*:"if true, then the first URL parameter can be empty without causing an error"`
	InputKind            EntityKind              `json:"inputKind,omitempty"   o*:"contains the kind of the expected input in the body"`
	InputMultiple        bool                    `json:"inputMultiple"         o*:"tells if it's a set of entities that is expected, or juste one entity"`
	InputDesc            string                  `json:"inputDesc"             o*:"contains a description of the input"`
	InputSchema          core.URL                `json:"inputSchema,omitempty" o*:"tells if it's a set of entities that is expected, or juste one entity"`
	IsOn                 bool                    `` /* 136-byte string literal not displayed */
	Method               string                  `json:"method"                o*:"the label for the associated HTTP method type"`
	MethodType           HTTPMethodType          `json:"-"                     o*:"which HTTP method (as an int code) does it responds to"`
	Protected            bool                    `json:"protected"             o*:"tells if a user must be logged to reach this operation or not"`
	Resource             *Resource               `json:"-"                     o*:"the resource to which this operation is attached"`
	ResourcePath         core.URL                `json:"resourcePath"          o*:"the path for the resource that this operation is associated with"`
	OutputMultiple       bool                    `json:"outputMultiple"        o*:"if true, then an array of instances of the resource is returned; else, a single entity"`
	OperationURL         core.URL                `json:"operationURL"          o*:"the URL = the path + the action"`
	IsSuperUserProtected bool                    `json:"isSuperUserProtected"  o*:"if true, then the operation is not visible nor usable for non-super users"`
	IsAdminProtected     bool                    `json:"isAdminProtected"      o*:"if true, then the operation is not visible nor usable for non-admin users"`
	QueryParams          []*WSQueryParam         `json:"queryParams"           o*:"the expected URL query parameters"`
	Responses            []*WebOperationResponse `json:"responses"             o*:"the possible responses, documented"`
	// contains filtered or unexported fields
}

WebOperation defines the structure of a web operation

func OnGET

func OnGET(entityKind EntityKind) *WebOperation

OnGET initialises a web operation for a given resource, for the HTTP method GET

func OnPOST

func OnPOST(entityKind EntityKind) *WebOperation

OnPOST initialises a web operation for a given resource, for the HTTP method POST

func RandomWebOperation

func RandomWebOperation(source rand.Source) *WebOperation

RandomWebOperation returns a randomly chosen WebOperation instance, given a random generation source

func UseGenericHandlerFor

func UseGenericHandlerFor(entityKind EntityKind, action GenericActionType, loadingID LoadingID, isAdminProtected bool) *WebOperation

UseGenericHandlerFor allows to easily deploy, for a particular entity kind, generic web operations, as provided by this framework

func (*WebOperation) ForAction

func (thisOperation *WebOperation) ForAction(actionType IActionType) *WebOperation

ForAction sets on a operation an action, which can be generic or custom, but should always be an IActionType instance

func (*WebOperation) GetOperationURL

func (thisOperation *WebOperation) GetOperationURL(context BiContext) core.URL

Returning the "contextual" operation's URL

func (*WebOperation) InShort

func (thisOperation *WebOperation) InShort(label string) *WebOperation

InShort allows to set the SHORTEST POSSIBLE description for this operation

func (*WebOperation) InitSchema

func (thisOperation *WebOperation) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity kind

func (*WebOperation) InputMany

func (thisOperation *WebOperation) InputMany(entityKind EntityKind) *WebOperation

InputMany allows to indicate the type of the entities expected as an input in the request body

func (*WebOperation) InputOne

func (thisOperation *WebOperation) InputOne(entityKind EntityKind) *WebOperation

InputOne allows to indicate the type of the single entity expected as an input in the request body

func (*WebOperation) IsAllowed

func (thisOperation *WebOperation) IsAllowed(user IUser) bool

IsAllowed tells is the given user can access this operation

func (*WebOperation) More

func (thisOperation *WebOperation) More(longDescription string) *WebOperation

More allows to add a longer description

func (*WebOperation) On

func (thisOperation *WebOperation) On() *WebOperation

On sets a web operation on "On" mode, i.e. allows it to be registered and active

func (*WebOperation) Open

func (thisOperation *WebOperation) Open() *WebOperation

Open enables an "open mode" for a web operation, i.e. allows clients to reach it without authentication

func (*WebOperation) OutputExample

func (thisOperation *WebOperation) OutputExample(httpStatus int, outputExamples ...IEntity) *WebOperation

OutputExample allows to provide an example for a response associated with an HTTP status code

func (*WebOperation) ProvideManyWith

func (thisOperation *WebOperation) ProvideManyWith(handlerFunction PluralResponseFunction, loadingID LoadingID) *WebOperation

ProvideManyWith allows to set a handler for a operation that should return a set of entities

func (*WebOperation) ProvideOneWith

func (thisOperation *WebOperation) ProvideOneWith(handlerFunction SingleResponseFunction, loadingID LoadingID) *WebOperation

ProvideOneWith allows to set a handler for a operation that should return 1 entity

func (*WebOperation) SearchWith

func (thisOperation *WebOperation) SearchWith(searchEntityKind EntityKind) *WebOperation

SearchWith allows to indicate the type of the simple search entity expected as an input in the request body

func (*WebOperation) SetAdminProtected

func (thisOperation *WebOperation) SetAdminProtected(protected bool) *WebOperation

SetAdminProtected allows to tell if a operation should be accessible for admin users only

func (*WebOperation) SetSuperUserProtected

func (thisOperation *WebOperation) SetSuperUserProtected(protected bool) *WebOperation

SetSuperUserProtected allows to tell if a operation should be accessible for admin users only

func (*WebOperation) WithBoolQueryParam

func (thisOperation *WebOperation) WithBoolQueryParam(name string, mandatory bool, description string) *WebOperation

WithBoolQueryParam allows to tell that a boolean URL query parameter can be expected by the operation

func (*WebOperation) WithDoubleQueryParam

func (thisOperation *WebOperation) WithDoubleQueryParam(name string, mandatory bool, description string) *WebOperation

WithDoubleQueryParam allows to tell that a double URL query parameter can be expected by the operation

func (*WebOperation) WithIntQueryParam

func (thisOperation *WebOperation) WithIntQueryParam(name string, mandatory bool, description string) *WebOperation

WithIntQueryParam allows to tell that an int URL query parameter can be expected by the operation

func (*WebOperation) WithOptionalParam

func (thisOperation *WebOperation) WithOptionalParam(firstParamLabel string) *WebOperation

WithOptionalParam does the same as WithParam but sets the parameter as optional

func (*WebOperation) WithParam

func (thisOperation *WebOperation) WithParam(firstParamLabel string) *WebOperation

WithParam is used to indicate that the web operation needs to retrieve the targeted resource with the primary reference or ID set in the URL. The given argument here should explain what this parameter is, like 'orderReference', 'userID', 'maxSearchResults'. For optimal readability, the parameter should be labeled_this_way.

func (*WebOperation) WithResponse

func (thisOperation *WebOperation) WithResponse(code int, description string, emptyBody bool, exampleInputs ...IEntity) *WebOperation

WithResponse allows to describe a potential response for this operation

func (*WebOperation) WithStringQueryParam

func (thisOperation *WebOperation) WithStringQueryParam(name string, mandatory bool, description string) *WebOperation

WithStringQueryParam allows to tell that a string URL query parameter can be expected by the operation

type WebOperationResponse

type WebOperationResponse struct {
	Entity             // is a particular kind of geen entity
	Code        int    `json:"code"        o*:"this response's HTTP code'"`
	Description string `json:"description" o*:"this response's description"`
	EmptyBody   bool   `json:"emptyBody"   o*:"if true, then the operation returns nothing"`
	// contains filtered or unexported fields
}

WebOperationResponse defines the structure of a web operation response, i.e. properties & links, plus basic methods

func NewWebOperationResponse

func NewWebOperationResponse() *WebOperationResponse

NewWebOperationResponse is a shortcut to instantiate a new WebOperationResponse

func (*WebOperationResponse) InitSchema

func (thisWebOperationResponse *WebOperationResponse) InitSchema() *EntitySchema

InitSchema is used to create a schema, to bear all the meta information about this entity type

type WsContext

type WsContext interface {
	AppContext
	GetFirstURLParameter() string // returns the first URL parameter, as in: rest/resource_name/action_name/first_param

	GetTargetEntityKind() EntityKind // returns the currently targeted entity kind

	GetInputEntity() IEntity // returns a pointer the entity that has been passed through the current request's body, e.g. *MyEntity

	GetInputEntitySlice() interface{} // returns the entities that has to passed through the current request's body; has to be cast as ([]*MyEntity)

	GetBiContext() BiContext // returns a BI context with some info coming from this WS context

	GetBoolQueryParam(name string) bool     // returns a query parameter value as a boolean
	GetIntQueryParam(name string) int       // returns a query parameter value as an int
	GetFloatQueryParam(name string) float64 // returns a query parameter value as a float64
	GetStringQueryParam(name string) string // returns a query parameter value as a string

	GetBody() []byte                    // gets the body from the context
	GetCurrentOperation() *WebOperation // what's the current web operation the user has called ?
	// contains filtered or unexported methods
}

WsContext is a context bearing the info required when we're in the WS layer

Source Files

Jump to

Keyboard shortcuts

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