table_rest

package
v1.0.53 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2024 License: MIT Imports: 41 Imported by: 0

README

Table CRUD

Documentation

Index

Constants

View Source
const ISO8601 = "2006-01-02T15:04:05.99999Z07:00"

ISO format for date

View Source
const ISO8601output = "2006-01-02T15:04:05.99999-0700"

ISO format for date

Variables

View Source
var Db8_vd = false
View Source
var DbType = "Postgres" // var DbType = "SQLite"
View Source
var PrePostTab = map[string]PrePostFx{
	"conv_geolocation": ConvGeolocation,
	"flush_priv_cache": PPFlushPrivCache,
	"slow_down_1sec":   SlowDown1Sec,
	"slow_down_2sec":   SlowDown2Sec,
	"slow_down_sec":    SlowDownSec,
}
View Source
var QueryConfig = []CrudQueryConfig{}
View Source
var StoredProcConfig = []CrudStoredProcConfig{}
View Source
var TableConfig = []CrudConfig{} // Table based end points

Functions

func AbsFloat64

func AbsFloat64(a float64) float64

AbsFloat64 returns the absolute value. Negatives are converted to positive.

func AddToPrePostTab

func AddToPrePostTab(name string, fx PrePostFx)

func AddValidationFunction

func AddValidationFunction(name string, fx ValidationFunction)

AddValidationFunction will add a new (or replace an existing) named validation. The default validations are email and us_zip.

func AppendConfig

func AppendConfig(sp []CrudStoredProcConfig, tp []CrudConfig, qp []CrudQueryConfig)

func AppendWhereUseRLS

func AppendWhereUseRLS(dd int, UseRLS []RLSColumns) string

addStmt := AppendWhereUseRLS ( CrudData.UseRLS )

func Assert

func Assert(b bool)

Assert assumes that 'b' is true - if not the program will fail and exit.

func BindFixer

func BindFixer(stmt string, vars []interface{}) (modStmt string, modVars []interface{}, names []string)

Convert from Postgres $1, ... $n to

SQLite 	- ?, ?, ? - with positional replacement
MySql 	- ?, ?, ? - with positional replacement
MariaDB 	- ?, ?, ? - with positional replacement
Oracle 	- :n0, :n1, :n2 - named and return names.

func BoolToYesNo

func BoolToYesNo(b bool) string

BoolToYesNo convers a boolena to a Yes/No value.

func CheckPriv

func CheckPriv(c *gin.Context, user_id, needs_priv string) (rv bool)

CheckPriv returns true if the specified user_id contains the requested privilage

func CheckTable

func CheckTable(DbSchema, TableName string) (err error)

func ConnectToDb

func ConnectToDb()

func Contains

func Contains(lookFor, has []string) (missing []string, allFound bool)

func DecryptText

func DecryptText(key, text []byte) ([]byte, error)

func DisConnectToDb

func DisConnectToDb()

DisConnectToDb() closes connection to databse.

func DumpParamsToLog

func DumpParamsToLog(when string, c *gin.Context)

func DumpStoredProcDefs

func DumpStoredProcDefs()

func EncryptText

func EncryptText(key, text []byte) ([]byte, error)

func EncryptTextIndexable

func EncryptTextIndexable(key, xiv, text []byte) ([]byte, error)

func EncryptTextToB64

func EncryptTextToB64(key, text []byte) string

func EncryptTextToB64Indexable

func EncryptTextToB64Indexable(key, iv, text []byte) string

func FindDataType

func FindDataType(colName string, colTypes []CrudColTypeData) (dt string, seq string, found bool)

if dt, found := FindDataType(colName, colTypes); found {

func FoundCol

func FoundCol(c *gin.Context, WhereCols []string, UseRLS []RLSColumns) (cols []string, colsData []interface{}, found bool)

cols, colsData, found := FoundCol ( c, CrudData.WhereCols ) Used in } else if cols, colsData, found := FoundCol(c, CrudData.WhereCols, CrudData.UseRLS); found {

func GenOrderBy

func GenOrderBy(c *gin.Context, CrudData *CrudConfig) (rv string, err error)

xyzzy5050 TODO - order by - change to Name, Name Desc, Name Asc xyzzy5050 - TODO - need document format for __order_by__

a, b
a, -b
1, -b etc.
1 asc, b desc etc.
1 asc, "b" desc etc.

xyzzy5050 - TODO - add this to "view-query" pre defined??? - if so how xyzzy5050 - TODO - JSON format for this [c1,c2,...] - then just parse JSON strings xyzzy5050 - TODO - __where__=[{"col":"name","op":,"val":}] => ["col":"name","ord":"asc|desc"]

func GenProjected

func GenProjected(ProjectedCols []string) (rv string)

func GenUUID

func GenUUID() string

func GenWhere

func GenWhere(cols []string, KeywordKeyColumn, TableName string, UseRLS []RLSColumns) string

GenWhere(cols) generates the WHERE clause for a table. Used in `func HandleCRUDPerTableRequests(c *gin.Context, CrudData *CrudConfig) {` this also handles the case where we havve specifed a __keyword__ column for full text search and adds in the and user_id=$1 for RLS.

func GetAllStoredProcNames

func GetAllStoredProcNames() (rv []string)

func GetColumnMap

func GetColumnMap(DbSchema, TableName string) (cm map[string]bool, err error)

func GetColumns

func GetColumns(rows pgx.Rows) (columns []string, err error)

--------------------------------------------------------------------------------------------------------------------------------------------

func GetDeleteNames

func GetDeleteNames(c *gin.Context, potentialCols []string, pkCol string, colTypes []CrudColTypeData) (inputData []interface{}, id string, err error)

GetUpdateNmaes returns the set of update columns and the data values for running an udpate. Creating Delete from Update!!!!! 3. Delete - xyzzy3421 xyzzy -- TODO xyzzy4800 -- implement multi-delete, change name for function. Document Test.

func GetInsertNames

func GetInsertNames(c *gin.Context, potentialCols []string, pkCol string, colTypes []CrudColTypeData, parameterList []ParamListItem) (cols, vals string, inputData []interface{}, id string, genId bool, idColName string, err error)

GetInsertNames returns the list of columns for an insert, the list of placeholders for PG substitution of values, the list of values, the primary key or an error.

func GetKeysFromMap

func GetKeysFromMap(m map[string]string) (keys []string)

func GetMapStringBool

func GetMapStringBool(c *gin.Context, key string) (s map[string]bool)

func GetNameList

func GetNameList(c *gin.Context) (names []string)

func GetQueryNames

func GetQueryNames(c *gin.Context, potentialCols []ParamListItem, StoredProcdureName, URIPath string) (inputData []interface{}, err error)

func GetStoredProcNames

func GetStoredProcNames(c *gin.Context, potentialCols []ParamListItem, StoredProcdureName, URIPath string) (vals string, inputData []interface{}, err error)
   type ParamListItem struct {
   	ReqVar    string // variable for GetVar()
   	ParamName string // Name of variable (Info Only)
   	AutoGen   bool
	Required  bool
   }
   type CrudStoredProcConfig struct {
   	URIPath             string          // Path that will reach this end point
   	AuthKey             bool            // Require an auth_key
   	JWTKey              bool            // Require a JWT token authentntication header
   	StoredProcedureName string          // Name of stored procedure to call.
   	TableNameList       []string        // table name update/used in call (Info Only)
   	ParameterList       []ParamListItem // Pairs of values
   }

vals, inputData, id, err := GetStoredProcNames(c, SPData.ParameterList, SPData.StoredProcedureName, SPData.URIPath)

func GetTypeCode

func GetTypeCode(ty string) (rv string)

func GetUpdateNames

func GetUpdateNames(c *gin.Context, potentialCols []string, pkCol string, colTypes []CrudColTypeData) (updCols string, inputData []interface{}, id string, err error)

GetUpdateNmaes returns the set of update columns and the data values for running an udpate.

func GetVar

func GetVar(name string, c *gin.Context) (found bool, value string)

func HalfLifeDecay

func HalfLifeDecay(startValue float64, timeSpanInSeconds float64, halfLifeInSeconds float64) float64

HalfLifeDecay xyzzy

func HandleCRUDPerTableRequests

func HandleCRUDPerTableRequests(c *gin.Context, CrudData *CrudConfig)

func HandleQueryConfig

func HandleQueryConfig(c *gin.Context, QueryData *CrudQueryConfig)

func HandleStoredProcedureConfig

func HandleStoredProcedureConfig(c *gin.Context, SPData *CrudStoredProcConfig)

------------------------------------------------------------------------------------------------------------------------------------------

func HasOrderByList

func HasOrderByList(c *gin.Context) bool

func HasRolePriv

func HasRolePriv(c *gin.Context, requiredAuthPrivilages []string) bool

func IfEmpty

func IfEmpty(s, dflt string) string

func InArray

func InArray(lookFor string, inArr []string) bool

func InArrayInt

func InArrayInt(lookFor int, inArr []int) bool

func InArrayStr

func InArrayStr(lookFor string, inArr []string) bool

func InArrayStrN

func InArrayStrN(lookFor string, inArr []string) int

func InitTableREST

func InitTableREST(router *gin.Engine)

func InjectGlobalValues

func InjectGlobalValues(c *gin.Context)

func IsANumber

func IsANumber(s string, www http.ResponseWriter, req *http.Request) (nv int, err error)

if n, err = IsANumber ( page, www, req ) ; err != nil {

func IsBool

func IsBool(s string) (ok bool)

IsBool returns true if one of the true/fals names

func IsHexNumber

func IsHexNumber(s string) (ok bool)

IsHexNumber returns true if composed of Optional 0x|0X followd by 0..9 a..f A..F

func IsIntString

func IsIntString(s string) bool

IsIntString returns true if the string is composed of 0..0 digigts optionally with a +- at beginning.

func IsNumber

func IsNumber(s string) (ok bool)

IsNumber returns true if the string is composed of 0..0 digigts optionally with a +- at beginning.

func IsTLS

func IsTLS(c *gin.Context) bool

func IsValidOrigin

func IsValidOrigin(c *gin.Context, origin string) (ok bool, err error)

func KeysFromMap

func KeysFromMap(a interface{}) (keys []string)

KeysFromMap returns an array of keys from a map.

This is used like this:

keys := KeysFromMap(nameMap)
sort.Strings(keys)
for _, key := range keys {
	val := nameMap[key]
	...
}

func LogIt

func LogIt(s string, x ...interface{})

func LogIt2 added in v1.0.51

func LogIt2(fp *os.File, s string, x ...interface{})

func MaxFloat64

func MaxFloat64(a, b float64) float64

MaxFloat64 returns the maximum of 2 float64 values.

func MethodReplace

func MethodReplace(c *gin.Context) (methodOut string)

MethodReplace returns a new method if __method__ is a get argument. This allows for testing of code just using get requests. That is very convenient from a browser.

func MinFloat64

func MinFloat64(a, b float64) float64

MinFloat64 returns the minimum of 2 float64 values.

func NameTransform

func NameTransform(URIPath string) (rv string)

func NonNull

func NonNull(listCols []string, row map[string]interface{}) (rv []interface{}, nonNullFlag bool)

func PGCheckStoredProcedureNameParams

func PGCheckStoredProcedureNameParams(fd PGProc) (err error)

func PGCheckTableColumns

func PGCheckTableColumns(tab PGTable) (err error)

func ParseAllParams

func ParseAllParams(c *gin.Context) (rv map[string]string, err error)

func ParseBool

func ParseBool(s string) (b bool)

ParseBool convers a string to bool based on the table of trueValues.

func ParserOrderBy

func ParserOrderBy(val string, c *gin.Context, CrudData *CrudConfig) (p, e []string)

func PrependCRUDConfigData

func PrependCRUDConfigData(gob GobType) error

func ReadCRUDConfiFile

func ReadCRUDConfiFile(fn string) error

func ReadThenAppendConfig

func ReadThenAppendConfig(jsonFile string) (err error)

func ResetLogFile added in v1.0.40

func ResetLogFile(newFp *os.File)

func RmTrailingSlash

func RmTrailingSlash(s string) string

func Round

func Round(input float64) float64

Round rouns a float64 to the nearest integer value.

func RoundToPennies

func RoundToPennies(f float64) float64

RoundToPennies generates a rouned to pennies value for a float64.

func RowsToInterface

func RowsToInterface(rows pgx.Rows) ([]map[string]interface{}, string, int)

func RunPostFunctions

func RunPostFunctions(c *gin.Context, SPData CrudBaseConfig, inData string) (outData string, err error)

func RunPreFunctions

func RunPreFunctions(c *gin.Context, SPData CrudBaseConfig) (err error)

------------------------------------------------------------------------------------------------------------------------------------------

func RunStmt

func RunStmt(stmt string, data ...interface{}) (err error)

RunStmt ( filelib.QtR( `drop table if exists get_columns_%{table_no%}`, mdata ) )

func SQLDelete

func SQLDelete(stmt string, data ...interface{}) (err error)

SQLDelete can run delete statements.

func SQLDeleteW

func SQLDeleteW(c *gin.Context, stmt string, data ...interface{}) (err error)

func SQLInsert

func SQLInsert(stmt string, data ...interface{}) (err error)

SQLInsert can run insert statements that do not return data.

func SQLInsertId

func SQLInsertId(stmt string, data ...interface{}) (id int64, err error)

SQLInsertId can run insert statements , returns database generated id.

func SQLInsertIdW

func SQLInsertIdW(c *gin.Context, stmt string, data ...interface{}) (id int64, err error)

SQLInsertId can run insert statements , returns database generated id.

func SQLInsertW

func SQLInsertW(c *gin.Context, stmt string, data ...interface{}) (err error)

SQLInsert can run insert statements that do not return data.

func SQLQuery

func SQLQuery(stmt string, data ...interface{}) (resultSet pgx.Rows, err error)

SQLQuery runs stmt and returns rows.

func SQLQueryRow

func SQLQueryRow(stmt string, data ...interface{}) (aRow pgx.Row)

SQLQueryRow queries a single row and returns that data. func SQLQueryRow(stmt string, data ...interface{}) (aRow *sql.Row) {

func SQLQueryRowW

func SQLQueryRowW(c *gin.Context, stmt string, data ...interface{}) (aRow pgx.Row)

func SQLQueryW

func SQLQueryW(c *gin.Context, stmt string, data ...interface{}) (resultSet pgx.Rows, err error)

SQLQuery runs stmt and returns rows.

func SQLSelect

func SQLSelect(stmt string, data ...interface{}) (resultSet pgx.Rows, err error)

SQLSelect is SQLQuery under a different name.

func SQLSelectRow

func SQLSelectRow(stmt string, data ...interface{}) (aRow pgx.Row)

SQLSelectRow is SQLQueryRow under a different name.

func SQLUpdate

func SQLUpdate(stmt string, data ...interface{}) (nr int, err error)

SQLUpdate can run update statements that do not return data.

func SQLUpdateW

func SQLUpdateW(c *gin.Context, stmt string, data ...interface{}) (nr int, err error)

func SaveCRUDConfigData

func SaveCRUDConfigData(gob GobType) error

func SaveCrudConfig

func SaveCrudConfig(file string, sp []CrudStoredProcConfig, tp []CrudConfig, qp []CrudQueryConfig) (err error)

func SelData

func SelData(db *pgxpool.Pool, q string, data ...interface{}) []map[string]interface{}

./crud-pg-check.go:52:18: cannot use conn (variable of type *pgxpool.Pool) as type *pgx.Conn in argument to SelData

func SelectInt

func SelectInt(stmt string, data ...interface{}) (n int)

n := SelectInt ( `SELECT nextval('"table_id_seq"') as "x"` )

func SetCORSHeaders

func SetCORSHeaders(c *gin.Context)

func SetJSONHeaders

func SetJSONHeaders(c *gin.Context)

func SetJsonHdr

func SetJsonHdr(c *gin.Context)

func SetJsonPHdr

func SetJsonPHdr(c *gin.Context)

func SetValue

func SetValue(c *gin.Context, name string, value string)

func SetupCRUD

func SetupCRUD(gcfg *data.BaseConfigType, acfg *data.AppConfig, ucfg *data.UploadConfig)

func SetupConnectToJwtAuth(xctx context.Context, xconn *pgxpool.Pool, gcfg *data.BaseConfigType, acfg *data.AppConfig, qcfg *data.QRConfig, log *os.File, xem email.EmailSender, lgr *zap.Logger, xmd *metrics.MetricsData) {

func SetupConnectToDb

func SetupConnectToDb(xctx context.Context, xconn *pgxpool.Pool)

func SetupProcCheck

func SetupProcCheck()

func SetupSQL

func SetupSQL(f *os.File)

func Sha1String

func Sha1String(s string) []byte

func SplitURI

func SplitURI(uri string) (result []string)
  1. Split URL path into components then match by components. /abc/def/ghi -> []{"abc","def","ghi"}

cleans URI

func ValidEmailAddress

func ValidEmailAddress(em string, data interface{}, data2 []string) bool

func ValidInList

func ValidInList(em string, data interface{}, data2 []string) bool

func ValidInListQry

func ValidInListQry(em string, data interface{}, dataX []string) bool

func ValidList

func ValidList(em string, data interface{}, data2 []string) bool

"list": ValidList,

func ValidListInsensitive

func ValidListInsensitive(em string, data interface{}, data2 []string) bool

"list_case_insensitive": ValidListInsensitive,

func ValidUSZip

func ValidUSZip(em string, data interface{}, data2 []string) bool

func ValidateInputParameters

func ValidateInputParameters(c *gin.Context, Input []*MuxInput) (pname string, err error)

ValidateInputParameters checks input values for type and value. Also processing of AltNames and Defaults. ORIG: func (mux *ServeMux) ValidateInputParameters(c *gin.Context, kInOrd int) (err error) {

func ValidateInputParametersMap

func ValidateInputParametersMap(c *gin.Context, CrudData CrudConfig, dMa map[string]string, method string) (err error)

ValidateInputParameters checks input values for type and value. Also processing of AltNames and Defaults.

func ValidatePrivs2

func ValidatePrivs2(c *gin.Context, RequiredAuthPrivs []string) error

ValidatePrivs returns an error if the specified privilage in the slice `RequiredAuthPrivs` is not in the set of privilates that the user has.

Similar to (in the DDL/PgSQL code): create or replace function q_qr_admin_HasPriv_user_id ( p_user_id uuid, p_priv_needed varchar )

old//func ValidatePrivs(c *gin.Context, RequiredAuthPrivs []string, xsp *CrudBaseConfig) error { old// old// if dbgo.IsDbOn("ignore-privs") { old// // log that flag is on to discard privilege requests -- IN Red old// dbgo.Printf("%(red) --ignore-privs-- is set in debug - ignoring all privilege checks - at:%(LF)\n") old// return nil old// } old// old// hasPriv := GetMapStringBool(c, "__privs_map__") old// old// for _, needPriv := range RequiredAuthPrivs { old// // lookup privs in list - if user has theses then - if missing - return nil old// if gotIt, ok := hasPriv[needPriv]; ok && gotIt { old// dbgo.Printf("%(cyan) at:%(LF) - user has %s\n", needPriv) old// } else { old// err := fmt.Errorf("Missing Required Privilege ->%s<-", needPriv) old// dbgo.Fprintf(os.Stderr, "\n\n%(red) at:%(LF) - user missing privilege ->%s<- -- early exit, returning Error:%s\n\n", needPriv, err) old// dbgo.Fprintf(logFilePtr, "\n{\"msg\":\"at:%(LF) - user missing privilege ->%s<- -- early exit, returning Error:%s\"}\n\n", needPriv, err) old// log_enc.LogPrivError(c, needPriv, fmt.Sprintf("%s", err)) old// return err old// } old// } old// old// dbgo.Fprintf(os.Stderr, "%(cyan) at:%(LF) - login not required - privilege passed\n") old// dbgo.Fprintf(logFilePtr, "{\"msg\":\"at:%(LF) - login not required - privilege passed\"}\n") old// return nil // All privilege tests passed, return success old//}

func ValidateStoredProcs

func ValidateStoredProcs(sp []CrudStoredProcConfig)

func ValidateValidationTypeAtCompileData

func ValidateValidationTypeAtCompileData(Input []*MuxInput, ns int) (err error)

Input []*MuxInput `json:"Input"` //

func ValidationFunctionCommon

func ValidationFunctionCommon(c *gin.Context, NoValidate bool, depth int,
	FxGetNameList func() []string,
	FxGetDataValue func(name string) (string, bool),
	FxSetDataValue func(name, val string),
	Input []*MuxInput,
	LogFileEncryptionKey string,
) (pname string, err error)

ValidationFunction checks input values for type and value. Also processing of AltNames and Defaults.

func YearsToSeconds

func YearsToSeconds(yr float64) (sec float64)

YearsToSeconds converts a number of years to seconds

Types

type AnUploadedFile

type AnUploadedFile struct {
	OriginalFileName string
	Id               string
	FileHash         string
}

type BodyConfig

type BodyConfig struct {
	ColumnName string
	ColumnPos  int
}

type CrudBaseConfig

type CrudBaseConfig struct {
	URIPath          string          // Path that will reach this end point
	JWTKey           bool            // Require a JWT token authentication header (logged in)
	APIKey           string          //
	TableNameList    []string        // table name update/used in call (Info Only)
	ParameterList    []ParamListItem // Pairs of values
	PreProc          []string        // Functions to call before the store procedure
	PreConfig        []string        //
	PostProc         []string        // Functions to call after the return from the S.P.
	PostConfig       []string        //
	NoDoc            bool            // Turn of documentation on this API
	DocTag           string          // Documentation tag for lookup and display of doc.
	AuthPrivs        []string        // Prives that are required to access this end point (requires login/auth_token/jwt)
	GET_InputList    []*MuxInput     // Validation of inputs for htis call, if len(0) then no validation takes place.
	PUT_InputList    []*MuxInput     // Validation of inputs for htis call, if len(0) then no validation takes place.
	POST_InputList   []*MuxInput     // Validation of inputs for htis call, if len(0) then no validation takes place.
	DELETE_InputList []*MuxInput     // Validation of inputs for htis call, if len(0) then no validation takes place.
	InputList        []*MuxInput     // Validation of inputs for htis call, if len(0) then no validation takes place. -- This is for "All" and excludes use of per-method stuff
	MuxName          string          // Name used for generation of code in desc.html
	NoValidate       bool            // Skip all validation - useful for items like files that do not have an active component.
	FileWhereDefined string          // debugging info on where the definition comes from
	Comment          string          //
	EncryptPat       string          // . - pass, e encrypt, ! ignore
}

type CrudColTypeData

type CrudColTypeData struct {
	Name    string `json:"ColTypeName"`
	Type    string `json:"ColTypeType"`
	SeqName string `json:"ColTypeSeqName"`
}

------------------------------------------------------------------------------------------------------------------------------------------

type CrudConfig

type CrudConfig struct {
	CrudBaseConfig
	MethodsAllowed      []string          `json:"MethodsAllowed"`      // Set of methods that are allowed
	TableName           string            `json:"TableName"`           // table name
	InsertCols          []string          `json:"InsertCols"`          // Valid columns for insert
	ColsTypes           []CrudColTypeData `json:"ColsTypes"`           // Type of columns for thins like 'box'
	InsertPkCol         string            `json:"InsertPkCol"`         // PK during insert
	UpdateCols          []string          `json:"UpdateCols"`          // Valid columns for update
	UpdatePkCol         string            `json:"UpdatePkCol"`         // PK during update
	DeleteCols          []string          `json:"DeleteCols"`          // Valid columns for delete
	DeletePkCol         string            `json:"DeletePkCol"`         // PK during delete
	WhereCols           []string          `json:"WhereCols"`           // Set of columns that can be used in the "where" clause.
	SelectPkCol         string            `json:"SelectPkCol"`         // PK during select
	OrderByCols         []string          `json:"OrderByCols"`         // Set of columns that can be used in the "order by" clause.
	SelectRequiresWhere bool              `json:"SelectRequiresWhere"` // if true, then where must be specified -- can not return entire table.
	ProjectedCols       []string          `json:"ProjectedCols"`       // Set of columns that are projected in a select (GET).
	InsertAuthPrivs     []string          `json:"InsertAuthPrivs"`     // Prives that are requried to access this end point (requires login/auth_token/jwt)
	UpdateAuthPrivs     []string          `json:"UpdateAuthPrivs"`     // Prives that are requried to access this end point (requires login/auth_token/jwt)
	DeleteAuthPrivs     []string          `json:"DeleteAuthPrivs"`     // Prives that are requried to access this end point (requires login/auth_token/jwt)
	SelectAuthPrivs     []string          `json:"SelectAuthPrivs"`     // Prives that are requried to access this end point (requires login/auth_token/jwt)
	KeywordSearch       []string          `json:"KeywordSearch"`       // List of columns that will have tsvector data safedn from.
	KeywordKeyColumn    string            `json:"KewordKeyColumn"`     // tsvector colum where prioritiezed data is stored.
	UseRLS              []RLSColumns      `json:"UseRLS"`              // Use Row Level Secuirty basesed on colums specified. (user_id=$1)
}

type CrudOutputFilter

type CrudOutputFilter struct {
	FilterName     string // Used on front end to pick "defined" filters
	InputType      RowOrColumn
	FilterFunction FilterFunctionType
}

type CrudQueryConfig

type CrudQueryConfig struct {
	CrudBaseConfig
	QueryString     string // "select ... from tables where {{.where}} {{.order_by}}
	SubQuery        []CrudSubQueryConfig
	PrimayTableName string // MuxName
	HeaderInfo      []HeaderConfig
	BodyInfo        []BodyConfig
	IsUpdate        bool
	IsDelete        bool
	IsInsert        bool
	SelectAuthPrivs []string // Prives that are required to access this end point (requires login/auth_token/jwt)

}

type CrudStoredProcConfig

type CrudStoredProcConfig struct {
	CrudBaseConfig             //
	StoredProcedureName string // Name of stored procedure to call.

	CallAuthPrivs []string `json:"CallAuthPrivs"` // Prives that are requried to access this end point (requires login/auth_token/jwt)
}

func GetStoredProcDefinition

func GetStoredProcDefinition(name string) (rv CrudStoredProcConfig, err error)

type CrudSubQueryConfig

type CrudSubQueryConfig struct {
	BindValues []string // [ "id" ]
	To         string   // event_list - place to put the data result.
	QueryTmpl  string   // select * from "event" where "item_id" = $1 order by "seq"

	PrimayTableName string // MuxName
	HeaderInfo      []HeaderConfig
	BodyInfo        []BodyConfig
	SubQuery        []CrudSubQueryConfig // Recursive

	TableNameList []string // MuxName -- PJS New
	NamedOptional string   // New PJS - for __include__ optional data as sub-query 	__include__=notes when running primary query
	Cached        bool     // New PJS - for __include__ optional data as sub-query 	cache values so as to not re-run query

	SelectAuthPrivs []string `json:"SelectAuthPrivs"` // Prives that are requried to access this end point (requires login/auth_token/jwt)

}

type DbColumnsType

type DbColumnsType struct {
	ColumnName string
	DBType     string
	TypeCode   string
}

type DbTableType

type DbTableType struct {
	TableName string
	DbColumns []DbColumnsType
}

func GetFunctionInformationSchema

func GetFunctionInformationSchema(FunctionName string, DbSchema string) (rv DbTableType, err error)

SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position FROM information_schema.routines

JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name

WHERE routines.specific_schema='public' ORDER BY routines.routine_name, parameters.ordinal_position;

type FilterFunctionType

type FilterFunctionType func(www http.ResponseWriter, req *http.Request, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

type GetStatusType

type GetStatusType struct {
	Status         string
	HttpStatusCode int    `json:"status_code"`
	Msg            string `json:"msg"`
}

------------------------------------------------------------------------------------------------------------------------------------------

type GobType

type GobType struct {
	StoredProcConfig []CrudStoredProcConfig `json:"StoredProcConfig"`
	TableConfig      []CrudConfig           `json:"TableConfig"`
	QueryConfig      []CrudQueryConfig      `json:"QueryConfig"`
}

type HeaderConfig

type HeaderConfig struct {
	ColumnTitle string
	ColumnName  string
	ColumnPos   int
}

type MuxInput

type MuxInput struct {
	Name                string      `json:"Name"`                           //	Field Name
	AltName             []string    `json:"AltName,omitempty"`              // Alternate names list - if ReqVar is not there then pull each of these and set as ReqVar
	Label               string      `json:"Label,omitempty"`                //	Used for auto-generation of forms - this is the printed label for input.
	Default             string      `json:"Dflt,omitempty"`                 //	Default if not specified in input
	Type                string      `json:"Ty"`                             //	Type { 's', 'i', 'f', 'u' }
	MinLen              int         `json:"MinLen"`                         //	If > 0 then the minimum length - not checked if 0
	MaxLen              int         `json:"MaxLen"`                         //	If > 0 then the maximum length - not checked if 0
	Required            bool        `json:"Required"`                       //	If true then this is a required value.
	Validate            string      `json:"Val,omitempty"`                  //	A named validation like "email" or "us_zip" can be extended with calls to AddValidationFunction
	ValidationData      interface{} `json:"ValData"`                        //	Set of Data
	ListCaseInsenstivie bool        `json:"ListCaseInsenstitive,omitempty"` // if true then convert to lower case before lookup ('s' type only)
	ListValues          []string    `json:"ListValues,omitempty"`           //	A named validation like "email" or "us_zip" can be extended with calls to AddValidationFunction
	IsSecret            bool        `json:"IsSecret"`                       // xyzzy TODO - do not log secret values (value replace with encrypted entry)
	LineFile            string      `json:"-"`                              //	What line was it called from
	MinVal              int64       `json:"MinVal"`                         //	Integer Value Range Inclusive
	MaxVal              int64       `json:"MaxValLen"`                      //	Integer Value Range Inclusive
	UseMinVal           bool        `json:"UseMinVal"`                      //	Integer Value Range Inclusive
	UseMaxVal           bool        `json:"UseMaxVal"`                      //	Integer Value Range Inclusive
	BindToName          string      `json:"BindToName,omitempty"`           // New - bind to this name in a struct. xyzzy TODO
	ReMatch             string      `json:"ReMatch,omitempty"`              // A regular expression that the input must match (strings)
	Comment             string      `json:"Comment,omitempty"`              //	A User Comment
	Schema              string      `json:"Schema,omitempty"`               // A JSON Schema for validation
}

type PGColumn

type PGColumn struct {
	ColumnName string
}

type PGProc

type PGProc struct {
	FunctionName string
	Columns      []PGColumn
}

type PGTable

type PGTable struct {
	TableName string
	Columns   []PGColumn
}

type ParamListItem

type ParamListItem struct {
	ReqVar    string // variable for GetVar()
	ParamName string // Name of variable (Checked v.s. stored procedure name variable names)
	AutoGen   string // TODO Is automatically generated value (think UUID, Random or Sequence)
	Required  bool   // Verify that value is supplied (check if this is implemented)
}

type PrePostFlag

type PrePostFlag int
const (
	PreFlag  PrePostFlag = 1
	PostFlag PrePostFlag = 2
)

type PrePostFx

type PrePostFx func(c *gin.Context, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

type RLSColumns

type RLSColumns struct {
	ColumnName       string `json:"ColumnName"`
	ContextValueName string `json:"ContextValueName"`
}

type RowOrColumn

type RowOrColumn int
const (
	IsSingleColumn RowOrColumn = 1
	IsEntireRow    RowOrColumn = 2
)

type StatusType

type StatusType int
const (
	OkContinueSaveOutData StatusType = 1
	OkDiscard             StatusType = 2
	ErrorFail             StatusType = 3
)

func ConvGeolocation

func ConvGeolocation(c *gin.Context, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

ConvGeolocation takes a single geolocation string value in the format a,b,c,d and converts it into a set of 8 values.

func PPFlushPrivCache

func PPFlushPrivCache(c *gin.Context, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

func SlowDown1Sec

func SlowDown1Sec(c *gin.Context, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

Can be used as eitehr a pre-or-post option.

func SlowDown2Sec

func SlowDown2Sec(c *gin.Context, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

func SlowDownSec

func SlowDownSec(c *gin.Context, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

type ValidationFunction

type ValidationFunction func(s string, data interface{}, data2 []string) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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