Documentation
¶
Index ¶
- Constants
- Variables
- func APIKeyBasedKeyGenerator(c fiber.Ctx) string
- func ApplyCountToQuery(query interface{}, count *GoDataCountQuery) interface{}
- func ApplyDefaultLimits(top *GoDataTopQuery, skip *GoDataSkipQuery, defaultTop int) (*GoDataTopQuery, *GoDataSkipQuery)
- func ClearProviderCache()
- func ConvertExpandItemToSQL(item *ExpandItem, entity *EntityMetadata) (string, error)
- func ConvertExpandToSQL(expand *GoDataExpandQuery, entity *EntityMetadata) ([]string, error)
- func ConvertFilterToSQL(ctx context.Context, filter *GoDataFilterQuery, metadata EntityMetadata) (string, []interface{}, error)
- func ConvertSelectToSQL(sel *GoDataSelectQuery, entity *EntityMetadata) ([]string, error)
- func ConvertTopSkipToSQL(top *GoDataTopQuery, skip *GoDataSkipQuery) (string, []interface{})
- func CustomKeyGenerator(fn func(c fiber.Ctx) string) func(c fiber.Ctx) string
- func FormatExpandExpression(expand *GoDataExpandQuery) string
- func FormatFilterExpression(filter *GoDataFilterQuery) string
- func FormatSelectExpression(sel *GoDataSelectQuery) string
- func FormatTopSkipForURL(top *GoDataTopQuery, skip *GoDataSkipQuery) string
- func GenerateJWT(claims jwt.MapClaims, config ...*JWTConfig) (string, error)
- func GenerateRefreshToken(claims jwt.MapClaims, config ...*JWTConfig) (string, error)
- func GetBasicAuthUsername(c fiber.Ctx) string
- func GetConnection(c fiber.Ctx) *sql.DB
- func GetCountLimit() int
- func GetCountSQLFragment(count *GoDataCountQuery, tableName string) string
- func GetCountValue(count *GoDataCountQuery) bool
- func GetCurrentTenant(c fiber.Ctx) string
- func GetDBFromContext(c fiber.Ctx) *sql.DB
- func GetExpandComplexity(expand *GoDataExpandQuery) int
- func GetExpandedProperties(expand *GoDataExpandQuery) []string
- func GetFilterComplexity(filter *GoDataFilterQuery) int
- func GetFilterProperties(filter *GoDataFilterQuery) []string
- func GetJWTClaims(c fiber.Ctx) jwt.MapClaims
- func GetSelectComplexity(sel *GoDataSelectQuery) int
- func GetSelectedProperties(sel *GoDataSelectQuery) []string
- func GetSkipValue(skip *GoDataSkipQuery) int
- func GetTopSkipComplexity(top *GoDataTopQuery, skip *GoDataSkipQuery) int
- func GetTopValue(top *GoDataTopQuery) int
- func HasRole(c fiber.Ctx, role string) bool
- func HasScope(c fiber.Ctx, scope string) bool
- func IsAdmin(c fiber.Ctx) bool
- func IsAuthenticated(c fiber.Ctx) bool
- func IsCountEnabled() bool
- func IsCountRequested(count *GoDataCountQuery) bool
- func IsSelectAll(sel *GoDataSelectQuery) bool
- func IsSimpleExpand(expand *GoDataExpandQuery) bool
- func IsSimpleFilter(filter *GoDataFilterQuery) bool
- func ParseExpandOption(ctx context.Context, queue *TokenQueue, item *ExpandItem) error
- func ParseTopSkipFromURL(topStr, skipStr string) (*GoDataTopQuery, *GoDataSkipQuery, error)
- func SanitizeInput(input string, config *ValidationConfig) string
- func SecurityHeadersMiddleware(config *SecurityHeadersConfig) fiber.Handler
- func SemanticizeFilterQuery(filter *GoDataFilterQuery, metadata EntityMetadata) error
- func SetSkipValue(skip *GoDataSkipQuery, value int) error
- func SetTopValue(top *GoDataTopQuery, value int) error
- func TenantBasedKeyGenerator(c fiber.Ctx) string
- func UserBasedKeyGenerator(c fiber.Ctx) string
- func ValidateCountLimit(estimatedCount int) error
- func ValidateCountParameter(params map[string]string) error
- func ValidateCountValue(count string) error
- func ValidateExpandDepth(expand []ExpandOption, maxDepth int, currentDepth int) error
- func ValidateExpandItem(item *ExpandItem, service *EntityService, entity *EntityMetadata) error
- func ValidateExpandQuery(expand *GoDataExpandQuery, service *EntityService, entity *EntityMetadata) error
- func ValidateFilterExpression(ctx context.Context, filter string, metadata EntityMetadata) error
- func ValidateFilterQuery(filter string, config *ValidationConfig) error
- func ValidateJWT(tokenString string, config ...*JWTConfig) (jwt.MapClaims, error)
- func ValidateOrderByQuery(orderBy string, config *ValidationConfig) error
- func ValidatePropertyName(name string, config *ValidationConfig) error
- func ValidateQueryOptions(options *QueryOptions, config *ValidationConfig) error
- func ValidateSearchQuery(search string, config *ValidationConfig) error
- func ValidateSelectProperty(propertyName string, entity *EntityMetadata) error
- func ValidateSelectQuery(sel *GoDataSelectQuery, service *EntityService, entity *EntityMetadata) error
- func ValidateSelectString(selectStr string, config *ValidationConfig) error
- func ValidateSkipQuery(skip *GoDataSkipQuery) error
- func ValidateSkipValue(skip int) error
- func ValidateTopQuery(top *GoDataTopQuery) error
- func ValidateTopSkipCombination(top *GoDataTopQuery, skip *GoDataSkipQuery) error
- func ValidateTopValue(top int, config *ValidationConfig) error
- type AssociationMetadata
- type Associativity
- type AuditLogConfig
- type AuditLogEntry
- type AuditLogger
- type AuditOperation
- type BaseEntityService
- func (s *BaseEntityService) BuildTypedKeyFilter(ctx context.Context, keys map[string]any) (*GoDataFilterQuery, error)
- func (s *BaseEntityService) Create(ctx context.Context, entity any) (any, error)
- func (s *BaseEntityService) Delete(ctx context.Context, keys map[string]any) error
- func (s *BaseEntityService) Get(ctx context.Context, keys map[string]any) (any, error)
- func (s *BaseEntityService) GetComputeFields(computeOption *ComputeOption) []PropertyMetadata
- func (s *BaseEntityService) GetCount(ctx context.Context, options QueryOptions) (int64, error)
- func (s *BaseEntityService) GetMetadata() EntityMetadata
- func (s *BaseEntityService) GetSearchableProperties() []PropertyMetadata
- func (s *BaseEntityService) ParseComputeQuery(ctx context.Context, computeStr string) (*ComputeOption, error)
- func (s *BaseEntityService) ParseSearchQuery(ctx context.Context, searchStr string) (*SearchOption, error)
- func (s *BaseEntityService) Patch(ctx context.Context, keys map[string]any, entity any) (any, error)
- func (s *BaseEntityService) Query(ctx context.Context, options QueryOptions) (*ODataResponse, error)
- func (s *BaseEntityService) Update(ctx context.Context, keys map[string]any, entity any) (any, error)
- type BaseEventArgs
- func (e *BaseEventArgs) CanCancel() bool
- func (e *BaseEventArgs) Cancel(reason string)
- func (e *BaseEventArgs) GetCancelReason() string
- func (e *BaseEventArgs) GetContext() *EventContext
- func (e *BaseEventArgs) GetEntity() interface{}
- func (e *BaseEventArgs) GetEntityName() string
- func (e *BaseEventArgs) GetEventType() EventType
- func (e *BaseEventArgs) GetManager() *ObjectManager
- func (e *BaseEventArgs) IsCanceled() bool
- func (e *BaseEventArgs) Manager() *ObjectManager
- func (e *BaseEventArgs) SetEntity(entity interface{})
- type BaseProvider
- func (p *BaseProvider) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func (p *BaseProvider) BuildLimitClause(skip, top int) string
- func (p *BaseProvider) BuildOrderByClause(orderBy string, metadata EntityMetadata) (string, error)
- func (p *BaseProvider) BuildSelectClause(selectFields []string, metadata EntityMetadata) (string, error)
- func (p *BaseProvider) BuildSelectQueryOptimized(ctx context.Context, metadata EntityMetadata, options QueryOptions) (string, []interface{}, error)
- func (p *BaseProvider) BuildWhereClause(filter string, metadata EntityMetadata) (string, []interface{}, error)
- func (p *BaseProvider) Close() error
- func (p *BaseProvider) ConvertValue(value interface{}, targetType string) (interface{}, error)
- func (p *BaseProvider) FormatDateTime(t time.Time) string
- func (p *BaseProvider) GetConnection() *sql.DB
- func (p *BaseProvider) GetDriverName() string
- func (p *BaseProvider) GetQueryBuilder() *QueryBuilder
- func (p *BaseProvider) InitParsers()
- func (p *BaseProvider) InitQueryBuilder()
- func (p *BaseProvider) MapGoTypeToSQL(goType string) string
- type BasicAuthConfig
- type BatchConfig
- type BatchHTTPOperation
- type BatchOperation
- type BatchOperationResponse
- type BatchPart
- type BatchProcessor
- type BatchRequest
- type BatchResponse
- type BatchResponsePart
- type Bool
- type ClientLimiter
- type ComplianceConfig
- type ComputeExpression
- type ComputeItem
- type ComputeOption
- type ComputeParser
- type ComputeTokenType
- type ConnectionConfig
- type DatabaseProvider
- type DefaultDialect
- func (d *DefaultDialect) BuildCeilingFunction(arg string) string
- func (d *DefaultDialect) BuildConcatFunction(args []string) string
- func (d *DefaultDialect) BuildDateExtractFunction(functionName, arg string) string
- func (d *DefaultDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
- func (d *DefaultDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
- func (d *DefaultDialect) BuildLimitClause(top, skip int) string
- func (d *DefaultDialect) BuildNowFunction() string
- func (d *DefaultDialect) BuildSubstringFromFunction(str, start string) string
- func (d *DefaultDialect) BuildSubstringFunction(str, start, length string) string
- func (d *DefaultDialect) FormatDateTime(t time.Time) string
- func (d *DefaultDialect) GetName() string
- func (d *DefaultDialect) QuoteIdentifier(identifier string) string
- func (d *DefaultDialect) SetupNodeMap() NodeMap
- func (d *DefaultDialect) SetupPrepareMap() PrepareMap
- func (d *DefaultDialect) SupportsFullTextSearch() bool
- type EntityAuthConfig
- type EntityCacheItem
- type EntityConfig
- type EntityContainerMetadata
- type EntityDeletedArgs
- type EntityDeletingArgs
- type EntityErrorArgs
- type EntityEventManager
- func (em *EntityEventManager) Clear()
- func (em *EntityEventManager) ClearEntity(entityName string)
- func (em *EntityEventManager) Emit(args EventArgs) error
- func (em *EntityEventManager) GetHandlerCount(eventType EventType, entityName string) int
- func (em *EntityEventManager) ListSubscriptions() map[string]interface{}
- func (em *EntityEventManager) Subscribe(eventType EventType, entityName string, handler EventHandler)
- func (em *EntityEventManager) SubscribeFunc(eventType EventType, entityName string, handler func(args EventArgs) error)
- func (em *EntityEventManager) SubscribeGlobal(eventType EventType, handler EventHandler)
- func (em *EntityEventManager) SubscribeGlobalFunc(eventType EventType, handler func(args EventArgs) error)
- type EntityGetArgs
- type EntityInsertedArgs
- type EntityInsertingArgs
- type EntityListArgs
- type EntityMapper
- type EntityMetadata
- type EntityModifiedArgs
- type EntityModifyingArgs
- type EntityOption
- type EntityService
- type EntitySetMetadata
- type EntityTypeMetadata
- type EntityValidatedArgs
- type EntityValidatingArgs
- type EnvConfig
- type EventArgs
- type EventContext
- type EventHandler
- type EventHandlerFunc
- type EventType
- type ExpandItem
- type ExpandOption
- type ExpandTokenType
- type ExpressionParser
- func (p *ExpressionParser) ConvertToFilterExpressions(node *ParseNode) ([]FilterExpression, error)
- func (p *ExpressionParser) InfixToPostfix(ctx context.Context, tokens []*Token) ([]*Token, error)
- func (p *ExpressionParser) ParseFilterExpression(ctx context.Context, filter string) (*ParseNode, error)
- func (p *ExpressionParser) PostfixToTree(ctx context.Context, postfix []*Token) (*ParseNode, error)
- type FiberContextKeyType
- type FileAuditLogger
- type FilterExpression
- type FilterOperator
- type FilterTokenType
- type Float64
- type GoDataComputeQuery
- type GoDataCountQuery
- type GoDataExpandQuery
- type GoDataFilterQuery
- type GoDataOrderByQuery
- type GoDataSearchQuery
- type GoDataSelectQuery
- func (s *GoDataSelectQuery) AddSelectItem(propertyName string)
- func (s *GoDataSelectQuery) GetSelectItemByProperty(propertyName string) *SelectItem
- func (s *GoDataSelectQuery) HasProperty(propertyName string) bool
- func (s *GoDataSelectQuery) RemoveSelectItem(propertyName string)
- func (s *GoDataSelectQuery) String() string
- type GoDataSkipQuery
- type GoDataTopQuery
- type IDGeneratorType
- type Int64
- type JWTConfig
- type ManyAssociationMetadata
- type MetadataResponse
- type MultiTenantConfig
- type MultiTenantEntityService
- func (s *MultiTenantEntityService) Create(ctx context.Context, entity any) (any, error)
- func (s *MultiTenantEntityService) Delete(ctx context.Context, keys map[string]any) error
- func (s *MultiTenantEntityService) ExecuteWithTenant(tenantID string, operation func(provider DatabaseProvider) error) error
- func (s *MultiTenantEntityService) Get(ctx context.Context, keys map[string]any) (any, error)
- func (s *MultiTenantEntityService) GetAvailableTenants() []string
- func (s *MultiTenantEntityService) GetCurrentTenantFromContext(ctx context.Context) string
- func (s *MultiTenantEntityService) GetTenantProvider(tenantID string) DatabaseProvider
- func (s *MultiTenantEntityService) GetTenantStats(tenantID string) map[string]interface{}
- func (s *MultiTenantEntityService) IsMultiTenantEnabled() bool
- func (s *MultiTenantEntityService) LogMultiTenantInfo()
- func (s *MultiTenantEntityService) Query(ctx context.Context, options QueryOptions) (*ODataResponse, error)
- func (s *MultiTenantEntityService) Update(ctx context.Context, keys map[string]any, entity any) (any, error)
- func (s *MultiTenantEntityService) ValidateTenantAccess(ctx context.Context, operation string) error
- func (s *MultiTenantEntityService) WithTenantContext(ctx context.Context, tenantID string) context.Context
- type MultiTenantProviderPool
- func (p *MultiTenantProviderPool) AddTenant(tenantID string, config *TenantConfig) error
- func (p *MultiTenantProviderPool) Close() error
- func (p *MultiTenantProviderPool) GetAllStats() map[string]interface{}
- func (p *MultiTenantProviderPool) GetProvider(tenantID string) DatabaseProvider
- func (p *MultiTenantProviderPool) GetTenantList() []string
- func (p *MultiTenantProviderPool) GetTenantStats(tenantID string) map[string]interface{}
- func (p *MultiTenantProviderPool) HealthCheck() map[string]interface{}
- func (p *MultiTenantProviderPool) InitializeProviders() error
- func (p *MultiTenantProviderPool) IsEnabled() bool
- func (p *MultiTenantProviderPool) RemoveTenant(tenantID string) error
- type MySQLDialect
- func (d *MySQLDialect) BuildCeilingFunction(arg string) string
- func (d *MySQLDialect) BuildConcatFunction(args []string) string
- func (d *MySQLDialect) BuildDateExtractFunction(functionName, arg string) string
- func (d *MySQLDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
- func (d *MySQLDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
- func (d *MySQLDialect) BuildLimitClause(top, skip int) string
- func (d *MySQLDialect) BuildNowFunction() string
- func (d *MySQLDialect) BuildSubstringFromFunction(str, start string) string
- func (d *MySQLDialect) BuildSubstringFunction(str, start, length string) string
- func (d *MySQLDialect) FormatDateTime(t time.Time) string
- func (d *MySQLDialect) GetName() string
- func (d *MySQLDialect) QuoteIdentifier(identifier string) string
- func (d *MySQLDialect) SetupNodeMap() NodeMap
- func (d *MySQLDialect) SetupPrepareMap() PrepareMap
- func (d *MySQLDialect) SupportsFullTextSearch() bool
- type MySQLProvider
- func (p *MySQLProvider) BuildDeleteQuery(entity EntityMetadata, keyValues map[string]interface{}) (string, []interface{}, error)
- func (p *MySQLProvider) BuildInsertQuery(entity EntityMetadata, data map[string]interface{}) (string, []interface{}, error)
- func (p *MySQLProvider) BuildSelectQuery(entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
- func (p *MySQLProvider) BuildUpdateQuery(entity EntityMetadata, data map[string]interface{}, ...) (string, []interface{}, error)
- func (p *MySQLProvider) Connect(connectionString string) error
- func (p *MySQLProvider) FormatDateTime(t time.Time) string
- func (p *MySQLProvider) MapGoTypeToSQL(goType string) string
- type NamedArgs
- type NavigationLink
- type NavigationPropertyMetadata
- type NoOpAuditLogger
- type NodeMap
- type ODataError
- func BadRequestError(message string) *ODataError
- func EntityNotFoundError(entityName string) *ODataError
- func InvalidFilterError(filter string) *ODataError
- func NewODataError(code, message string) *ODataError
- func NewODataErrorWithTarget(code, message, target string) *ODataError
- func PropertyNotFoundError(propertyName, entityName string) *ODataError
- type ODataErrorDetail
- type ODataParser
- func (p *ODataParser) ParseExpand(expand string) ([]ExpandOption, error)
- func (p *ODataParser) ParseFilter(filter string) ([]FilterExpression, error)
- func (p *ODataParser) ParseOrderBy(orderBy string) ([]OrderByExpression, error)
- func (p *ODataParser) ParseQueryOptions(values url.Values) (QueryOptions, error)
- func (p *ODataParser) ParseQueryOptionsWithConfig(values url.Values, config ComplianceConfig) (QueryOptions, error)
- func (p *ODataParser) ValidateQueryOptions(options QueryOptions) error
- type ODataResponse
- type ODataService
- type ObjectManager
- func (om *ObjectManager) ApplyCachedUpdates() error
- func (om *ObjectManager) BeginTransaction() (*TxManager, error)
- func (om *ObjectManager) ClearCache() error
- func (om *ObjectManager) CommitTransaction(tx *TxManager) error
- func (om *ObjectManager) Evict(entity any) error
- func (om *ObjectManager) ExecuteQuery(query string, args ...any) (*sql.Rows, error)
- func (om *ObjectManager) ExecuteQueryTransaction(tx *TxManager, query string, args ...any) (*sql.Rows, error)
- func (om *ObjectManager) Find(entityName string, key string) (any, error)
- func (om *ObjectManager) FindCached(entityName string, key string) (any, error)
- func (om *ObjectManager) Flush(entity any) error
- func (om *ObjectManager) FlushAll() error
- func (om *ObjectManager) GetCachedCount() int
- func (om *ObjectManager) GetChangedObjects() []any
- func (om *ObjectManager) GetConnection() *sql.DB
- func (om *ObjectManager) HasAnyChanges() bool
- func (om *ObjectManager) HasChanges(entity any) bool
- func (om *ObjectManager) IsAttached(entity any) bool
- func (om *ObjectManager) IsCached(entityName string, key string) bool
- func (om *ObjectManager) Merge(entity any) (any, error)
- func (om *ObjectManager) Remove(entity any) error
- func (om *ObjectManager) RollbackTransaction(tx *TxManager) error
- func (om *ObjectManager) Save(entity any) error
- func (om *ObjectManager) SaveOrUpdate(entity any) error
- func (om *ObjectManager) SetBatchSize(size int)
- func (om *ObjectManager) SetCachedUpdates(enabled bool)
- func (om *ObjectManager) Update(entity any) error
- func (om *ObjectManager) WithTransaction(fn func(*TxManager) error) error
- type OperatorInfo
- type OptimizedComplianceConfig
- type OracleDialect
- func (d *OracleDialect) BuildCeilingFunction(arg string) string
- func (d *OracleDialect) BuildConcatFunction(args []string) string
- func (d *OracleDialect) BuildDateExtractFunction(functionName, arg string) string
- func (d *OracleDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
- func (d *OracleDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
- func (d *OracleDialect) BuildLimitClause(top, skip int) string
- func (d *OracleDialect) BuildNowFunction() string
- func (d *OracleDialect) BuildSubstringFromFunction(str, start string) string
- func (d *OracleDialect) BuildSubstringFunction(str, start, length string) string
- func (d *OracleDialect) FormatDateTime(t time.Time) string
- func (d *OracleDialect) GetName() string
- func (d *OracleDialect) QuoteIdentifier(identifier string) string
- func (d *OracleDialect) SetupNodeMap() NodeMap
- func (d *OracleDialect) SetupPrepareMap() PrepareMap
- func (d *OracleDialect) SupportsFullTextSearch() bool
- type OracleProvider
- func (p *OracleProvider) BuildDeleteQuery(entity EntityMetadata, keyValues map[string]interface{}) (string, []interface{}, error)
- func (p *OracleProvider) BuildInsertQuery(entity EntityMetadata, data map[string]interface{}) (string, []interface{}, error)
- func (p *OracleProvider) BuildSelectQuery(entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
- func (p *OracleProvider) BuildSelectQueryOptimized(ctx context.Context, entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
- func (p *OracleProvider) BuildUpdateQuery(entity EntityMetadata, data map[string]interface{}, ...) (string, []interface{}, error)
- func (p *OracleProvider) BuildWhereClause(filter string, metadata EntityMetadata) (string, []interface{}, error)
- func (p *OracleProvider) Connect(connectionString string) error
- func (p *OracleProvider) ConvertValue(value interface{}, targetType string) (interface{}, error)
- func (p *OracleProvider) FormatDateTime(t time.Time) string
- func (p *OracleProvider) GetDriverName() string
- func (p *OracleProvider) MapGoTypeToSQL(goType string) string
- type OrderByDirection
- type OrderByExpression
- type OrderByItem
- type OrderedEntity
- func (e *OrderedEntity) Get(name string) (interface{}, bool)
- func (e *OrderedEntity) MarshalJSON() ([]byte, error)
- func (e *OrderedEntity) Set(name string, value interface{})
- func (e *OrderedEntity) SetNavigationProperty(name string, navigationURL string)
- func (e *OrderedEntity) ToMap() map[string]interface{}
- func (e *OrderedEntity) UnmarshalJSON(data []byte) error
- type OrderedEntityResponse
- type OrderedProperty
- type PaginationInfo
- type ParseNode
- type PatchOperation
- type PostgreSQLDialect
- func (d *PostgreSQLDialect) BuildCeilingFunction(arg string) string
- func (d *PostgreSQLDialect) BuildConcatFunction(args []string) string
- func (d *PostgreSQLDialect) BuildDateExtractFunction(functionName, arg string) string
- func (d *PostgreSQLDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
- func (d *PostgreSQLDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
- func (d *PostgreSQLDialect) BuildLimitClause(top, skip int) string
- func (d *PostgreSQLDialect) BuildNowFunction() string
- func (d *PostgreSQLDialect) BuildSubstringFromFunction(str, start string) string
- func (d *PostgreSQLDialect) BuildSubstringFunction(str, start, length string) string
- func (d *PostgreSQLDialect) FormatDateTime(t time.Time) string
- func (d *PostgreSQLDialect) GetName() string
- func (d *PostgreSQLDialect) QuoteIdentifier(identifier string) string
- func (d *PostgreSQLDialect) SetupNodeMap() NodeMap
- func (d *PostgreSQLDialect) SetupPrepareMap() PrepareMap
- func (d *PostgreSQLDialect) SupportsFullTextSearch() bool
- type PostgreSQLProvider
- func (p *PostgreSQLProvider) BuildDeleteQuery(entity EntityMetadata, keyValues map[string]interface{}) (string, []interface{}, error)
- func (p *PostgreSQLProvider) BuildInsertQuery(entity EntityMetadata, data map[string]interface{}) (string, []interface{}, error)
- func (p *PostgreSQLProvider) BuildSelectQuery(entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
- func (p *PostgreSQLProvider) BuildUpdateQuery(entity EntityMetadata, data map[string]interface{}, ...) (string, []interface{}, error)
- func (p *PostgreSQLProvider) BuildWhereClause(filter string, metadata EntityMetadata) (string, []interface{}, error)
- func (p *PostgreSQLProvider) Connect(connectionString string) error
- func (p *PostgreSQLProvider) FormatDateTime(t time.Time) string
- func (p *PostgreSQLProvider) MapGoTypeToSQL(goType string) string
- type PrepareMap
- type PropertyMetadata
- type PropertyTypeMetadata
- type QueryBuilder
- func (qb *QueryBuilder) BuildCompleteQuery(ctx context.Context, metadata EntityMetadata, options QueryOptions) (string, []interface{}, error)
- func (qb *QueryBuilder) BuildComputeSQL(ctx context.Context, computeOption *ComputeOption, metadata EntityMetadata) (string, []interface{}, error)
- func (qb *QueryBuilder) BuildLimitClause(top, skip int) string
- func (qb *QueryBuilder) BuildOrderByClause(metadata EntityMetadata, orderByOptions []OrderByExpression) string
- func (qb *QueryBuilder) BuildSearchSQL(ctx context.Context, searchOption *SearchOption, metadata EntityMetadata) (string, []interface{}, error)
- func (qb *QueryBuilder) BuildSearchWhereClause(ctx context.Context, searchOption *SearchOption, metadata EntityMetadata) (string, []interface{}, error)
- func (qb *QueryBuilder) BuildSelectClause(metadata EntityMetadata, selectOptions []string) string
- func (qb *QueryBuilder) BuildWhereClause(ctx context.Context, tree *ParseNode, metadata EntityMetadata) (string, []interface{}, error)
- func (qb *QueryBuilder) BuildWhereClauseNamed(ctx context.Context, tree *ParseNode, metadata EntityMetadata, ...) (string, error)
- func (qb *QueryBuilder) CombineSearchWithFilter(ctx context.Context, searchSQL, filterSQL string, ...) (string, []interface{}, error)
- func (qb *QueryBuilder) QuoteIdentifier(identifier string) string
- type QueryOptions
- type QueryParseError
- type RateLimitConfig
- type RateLimitInfo
- type RateLimiter
- type RelationshipMetadata
- type ResponseField
- type ResponseNavigationLink
- type SQLDialect
- type SchemaMetadata
- type SearchExpression
- type SearchExpressionType
- type SearchOption
- type SearchParser
- func (p *SearchParser) ExtractSearchTerms(expr *SearchExpression) []string
- func (p *SearchParser) GetSearchComplexity(expr *SearchExpression) int
- func (p *SearchParser) GetSearchableProperties(metadata EntityMetadata) []PropertyMetadata
- func (p *SearchParser) OptimizeSearchExpression(expr *SearchExpression) *SearchExpression
- func (p *SearchParser) ParseSearch(ctx context.Context, searchStr string) (*SearchOption, error)
- func (p *SearchParser) ValidateSearchExpression(expr *SearchExpression) error
- type SearchTokenType
- type SecurityHeadersConfig
- type SelectItem
- type SemanticType
- type Server
- func (s *Server) Add(methods []string, path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) All(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) ApplyConfig(config *ServerConfig) *Server
- func (s *Server) AutoRegisterEntities(entities map[string]interface{}) error
- func (s *Server) CheckEntityReadOnly(entityName string, method string) fiber.Handler
- func (s *Server) DatabaseMiddleware() fiber.Handler
- func (s *Server) Delete(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) DisableRateLimit() *Server
- func (s *Server) GenerateJWT(claims jwt.MapClaims, config ...*JWTConfig) (string, error)
- func (s *Server) GenerateRefreshToken(claims jwt.MapClaims, config ...*JWTConfig) (string, error)
- func (s *Server) Get(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) GetAddress() string
- func (s *Server) GetConfig() *ServerConfig
- func (s *Server) GetEntities() map[string]EntityService
- func (s *Server) GetEntityAuth(name string) (EntityAuthConfig, bool)
- func (s *Server) GetEntityService(name string) EntityService
- func (s *Server) GetEventManager() *EntityEventManager
- func (s *Server) GetHandler() *fiber.App
- func (s *Server) GetRateLimitConfig() *RateLimitConfig
- func (s *Server) GetRouter() *fiber.App
- func (s *Server) Group(prefix string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) HandleBatch(c fiber.Ctx) error
- func (s *Server) Head(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) Install() error
- func (s *Server) IsRunning() bool
- func (s *Server) IsRunningAsService() bool
- func (s *Server) MultiTenantHealthCheck() fiber.Handler
- func (s *Server) NewRouterBasicAuth(validator func(string, string) bool, config ...*BasicAuthConfig) fiber.Handler
- func (s *Server) NewRouterJWTAuth(config ...*JWTConfig) fiber.Handler
- func (s *Server) OnEntityDeleted(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityDeletedGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityDeleting(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityDeletingGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityError(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityErrorGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityGet(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityGetGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityInserted(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityInsertedGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityInserting(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityInsertingGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityList(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityListGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityModified(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityModifiedGlobal(handler func(args EventArgs) error)
- func (s *Server) OnEntityModifying(entityName string, handler func(args EventArgs) error)
- func (s *Server) OnEntityModifyingGlobal(handler func(args EventArgs) error)
- func (s *Server) Options(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) Patch(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) PayloadLoggerMiddleware() fiber.Handler
- func (s *Server) Post(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) Put(path string, handlers ...fiber.Handler) fiber.Router
- func (s *Server) RateLimitMiddleware() fiber.Handler
- func (s *Server) RegisterEntity(name string, entity interface{}, opts ...EntityOption) error
- func (s *Server) RegisterEntityWithService(name string, service EntityService) error
- func (s *Server) RequireEntityAuth(entityName string) fiber.Handler
- func (s *Server) RequireTenant(allowedTenants ...string) fiber.Handler
- func (s *Server) Restart() error
- func (s *Server) SetAllowedHeaders(headers []string) *Server
- func (s *Server) SetAllowedMethods(methods []string) *Server
- func (s *Server) SetAllowedOrigins(origins []string) *Server
- func (s *Server) SetAuditLog(enabled bool, logType string) *Server
- func (s *Server) SetCORS(enabled bool) *Server
- func (s *Server) SetEnableLogging(enabled bool) *Server
- func (s *Server) SetHost(host string) *Server
- func (s *Server) SetLogLevel(level string) *Server
- func (s *Server) SetMaxRequestSize(size int64) *Server
- func (s *Server) SetPort(port int) *Server
- func (s *Server) SetProvider(provider DatabaseProvider) *Server
- func (s *Server) SetRateLimit(requestsPerMinute, burstSize int) *Server
- func (s *Server) SetRateLimitConfig(config *RateLimitConfig)
- func (s *Server) SetRoutePrefix(prefix string) *Server
- func (s *Server) SetSecurityHeaders(enabled bool) *Server
- func (s *Server) SetShutdownTimeout(timeout time.Duration) *Server
- func (s *Server) SetTLS(certFile, keyFile string) *Server
- func (s *Server) Shutdown() error
- func (s *Server) Start() error
- func (s *Server) Status() (service.Status, error)
- func (s *Server) Stop() error
- func (s *Server) TenantInfo() fiber.Handler
- func (s *Server) TenantMiddleware() fiber.Handler
- func (s *Server) TenantRateLimitMiddleware(requestsPerMinute int) fiber.Handler
- func (s *Server) TenantStatsMiddleware() fiber.Handler
- func (s *Server) TenantSwitchMiddleware() fiber.Handler
- func (s *Server) Uninstall() error
- func (s *Server) Use(args ...interface{}) fiber.Router
- func (s *Server) ValidateJWT(tokenString string, config ...*JWTConfig) (jwt.MapClaims, error)
- type ServerConfig
- type ServiceWrapper
- type StderrAuditLogger
- type StdoutAuditLogger
- type String
- type TenantConfig
- type TenantContextKeyType
- type Time
- type Token
- type TokenQueue
- func (q *TokenQueue) Dequeue() *Token
- func (q *TokenQueue) Empty() bool
- func (q *TokenQueue) Enqueue(token *Token)
- func (q *TokenQueue) GetValue() string
- func (q *TokenQueue) GetValueUntilSeparator() string
- func (q *TokenQueue) Peek() *Token
- func (q *TokenQueue) Reset()
- func (q *TokenQueue) Size() int
- func (q *TokenQueue) ToSlice() []*Token
- type TokenStack
- type Tokenizer
- type TxManager
- type URLParser
- func (up *URLParser) CleanODataValue(value string) string
- func (up *URLParser) ClearCache()
- func (up *URLParser) ExtractODataSystemParams(values url.Values) map[string]string
- func (up *URLParser) GetCacheStats() (normalizeEntries, validateEntries, simpleEntries int)
- func (up *URLParser) NormalizeODataQuery(query string) string
- func (up *URLParser) NormalizeODataQueryFast(query string) string
- func (up *URLParser) ParseExpandValue(value string) (string, error)
- func (up *URLParser) ParseFilterValue(value string) (string, error)
- func (up *URLParser) ParseODataURL(rawURL string) (*url.URL, url.Values, error)
- func (up *URLParser) ParseQuery(rawQuery string) (url.Values, error)
- func (up *URLParser) ParseQueryFast(rawQuery string) (url.Values, error)
- func (up *URLParser) ValidateODataQuery(query string) error
- func (up *URLParser) ValidateODataQueryFast(query string) error
- type UserIdentity
- type ValidationConfig
Constants ¶
const ( DefaultMaxFilterLength = 5000 // 5KB max filter string DefaultMaxSearchLength = 1000 // 1KB max search string DefaultMaxSelectLength = 1000 // 1KB max select string DefaultMaxOrderByLength = 500 // 500 bytes max orderby string DefaultMaxExpandDepth = 5 // Max 5 levels of expand nesting DefaultMaxTopValue = 1000 // Max 1000 records per page DefaultMaxSkipValue = 100000 // Max skip value )
Validation Limits
const ( DefaultRateLimitPerMinute = 100 // 100 requests per minute DefaultRateLimitBurstSize = 10 // Allow 10 concurrent requests DefaultRateLimitWindow = time.Minute // 1 minute window )
Rate Limiting
const ( DefaultMinConnections = 2 // Min connections per pool DefaultMaxConnections = 10 // Max connections per pool DefaultMaxIdleTime = 10 * time.Minute // Max idle time DefaultConnMaxLifetime = time.Hour // Max connection lifetime )
Connection Pool
const ( DefaultPageSize = 50 // Default page size if $top not specified DefaultTimeout = 30 * time.Second // Default query timeout )
Query Defaults
const ( MinJWTSecretLength = 32 // Minimum JWT secret length DefaultTokenExpiration = 15 * time.Minute // Default access token expiration DefaultRefreshExpiration = 7 * 24 * time.Hour // 7 days refresh token )
Security
const ( DefaultHealthCheckPeriod = 30 * time.Second // Health check interval MaxFailureCount = 3 // Mark unhealthy after 3 failures )
Health Check
const ( MaxPropertyNameLength = 100 // Max property name length PropertyNamePattern = `^[a-zA-Z0-9_\.]+$` // Allowed chars in property names )
Property Name Validation
const ( DefaultTopLimit = DefaultMaxTopValue // Usa constante centralizada DefaultSkipLimit = DefaultMaxSkipValue // Usa constante centralizada MinTopValue = 0 MinSkipValue = 0 )
Constantes para limites padrão
const (
MaxLogEntrySize = 10000 // Max size of single log entry
)
Logging
const (
UserContextKey = "user" // Chave para armazenar usuário no contexto
)
Constantes para chaves do contexto
Variables ¶
var FiberContextKey = FiberContextKeyType{}
var GlobalExpandTokenizer = NewExpandTokenizer()
GlobalExpandTokenizer é o tokenizer global singleton para $expand
var TenantContextKey = TenantContextKeyType{}
Functions ¶
func APIKeyBasedKeyGenerator ¶
APIKeyBasedKeyGenerator gera chave baseada na API key
func ApplyCountToQuery ¶
func ApplyCountToQuery(query interface{}, count *GoDataCountQuery) interface{}
ApplyCountToQuery aplica a configuração de count a uma query
func ApplyDefaultLimits ¶
func ApplyDefaultLimits(top *GoDataTopQuery, skip *GoDataSkipQuery, defaultTop int) (*GoDataTopQuery, *GoDataSkipQuery)
ApplyDefaultLimits aplica limites padrão se não especificados
func ClearProviderCache ¶
func ClearProviderCache()
ClearProviderCache limpa o cache de providers (útil para testes)
func ConvertExpandItemToSQL ¶
func ConvertExpandItemToSQL(item *ExpandItem, entity *EntityMetadata) (string, error)
ConvertExpandItemToSQL converte um item de expansão para SQL JOIN
func ConvertExpandToSQL ¶
func ConvertExpandToSQL(expand *GoDataExpandQuery, entity *EntityMetadata) ([]string, error)
ConvertExpandToSQL converte uma query de expansão para SQL
func ConvertFilterToSQL ¶
func ConvertFilterToSQL(ctx context.Context, filter *GoDataFilterQuery, metadata EntityMetadata) (string, []interface{}, error)
ConvertFilterToSQL converte uma GoDataFilterQuery para SQL
func ConvertSelectToSQL ¶
func ConvertSelectToSQL(sel *GoDataSelectQuery, entity *EntityMetadata) ([]string, error)
ConvertSelectToSQL converte uma query de seleção para SQL
func ConvertTopSkipToSQL ¶
func ConvertTopSkipToSQL(top *GoDataTopQuery, skip *GoDataSkipQuery) (string, []interface{})
ConvertTopSkipToSQL converte $top e $skip para SQL LIMIT e OFFSET
func CustomKeyGenerator ¶
CustomKeyGenerator cria um gerador de chave customizado
func FormatExpandExpression ¶
func FormatExpandExpression(expand *GoDataExpandQuery) string
FormatExpandExpression formata uma expressão de expansão para exibição
func FormatFilterExpression ¶
func FormatFilterExpression(filter *GoDataFilterQuery) string
FormatFilterExpression formata uma expressão de filtro para exibição
func FormatSelectExpression ¶
func FormatSelectExpression(sel *GoDataSelectQuery) string
FormatSelectExpression formata uma expressão de seleção para exibição
func FormatTopSkipForURL ¶
func FormatTopSkipForURL(top *GoDataTopQuery, skip *GoDataSkipQuery) string
FormatTopSkipForURL formata $top e $skip para URL
func GenerateJWT ¶
GenerateJWT gera um token JWT (função standalone)
func GenerateRefreshToken ¶
GenerateRefreshToken gera um refresh token (função standalone)
func GetBasicAuthUsername ¶
GetBasicAuthUsername retorna o username do Basic Auth do contexto
func GetConnection ¶
GetConnection retorna a conexão SQL do fiber context
func GetCountLimit ¶
func GetCountLimit() int
GetCountLimit retorna o limite máximo para operações de count
func GetCountSQLFragment ¶
func GetCountSQLFragment(count *GoDataCountQuery, tableName string) string
GetCountSQLFragment retorna o fragmento SQL para count se necessário
func GetCountValue ¶
func GetCountValue(count *GoDataCountQuery) bool
GetCountValue retorna o valor booleano do count
func GetCurrentTenant ¶
GetCurrentTenant retorna o tenant atual do contexto
func GetDBFromContext ¶
GetDBFromContext obtém a conexão de banco de dados do contexto DEPRECADO: Use GetConnection() do context_helpers.go que retorna o pool global
func GetExpandComplexity ¶
func GetExpandComplexity(expand *GoDataExpandQuery) int
GetExpandComplexity calcula a complexidade de uma query de expansão
func GetExpandedProperties ¶
func GetExpandedProperties(expand *GoDataExpandQuery) []string
GetExpandedProperties retorna as propriedades expandidas
func GetFilterComplexity ¶
func GetFilterComplexity(filter *GoDataFilterQuery) int
GetFilterComplexity retorna um score de complexidade do filtro
func GetFilterProperties ¶
func GetFilterProperties(filter *GoDataFilterQuery) []string
GetFilterProperties retorna todas as propriedades usadas no filtro
func GetJWTClaims ¶
GetJWTClaims retorna os claims do token JWT do contexto
func GetSelectComplexity ¶
func GetSelectComplexity(sel *GoDataSelectQuery) int
GetSelectComplexity calcula a complexidade de uma query de seleção
func GetSelectedProperties ¶
func GetSelectedProperties(sel *GoDataSelectQuery) []string
GetSelectedProperties retorna as propriedades selecionadas
func GetSkipValue ¶
func GetSkipValue(skip *GoDataSkipQuery) int
GetSkipValue retorna o valor de $skip
func GetTopSkipComplexity ¶
func GetTopSkipComplexity(top *GoDataTopQuery, skip *GoDataSkipQuery) int
GetTopSkipComplexity calcula a complexidade de $top e $skip
func IsAuthenticated ¶
IsAuthenticated verifica se o usuário está autenticado
func IsCountEnabled ¶
func IsCountEnabled() bool
IsCountEnabled verifica se o count está habilitado globalmente
func IsCountRequested ¶
func IsCountRequested(count *GoDataCountQuery) bool
IsCountRequested verifica se o count foi solicitado
func IsSelectAll ¶
func IsSelectAll(sel *GoDataSelectQuery) bool
IsSelectAll verifica se a seleção inclui todas as propriedades
func IsSimpleExpand ¶
func IsSimpleExpand(expand *GoDataExpandQuery) bool
IsSimpleExpand verifica se é uma expansão simples (sem opções aninhadas)
func IsSimpleFilter ¶
func IsSimpleFilter(filter *GoDataFilterQuery) bool
IsSimpleFilter verifica se o filtro é uma expressão simples (propriedade operador valor)
func ParseExpandOption ¶
func ParseExpandOption(ctx context.Context, queue *TokenQueue, item *ExpandItem) error
ParseExpandOption faz o parsing de uma opção de expansão
func ParseTopSkipFromURL ¶
func ParseTopSkipFromURL(topStr, skipStr string) (*GoDataTopQuery, *GoDataSkipQuery, error)
ParseTopSkipFromURL faz o parsing de $top e $skip de parâmetros de URL
func SanitizeInput ¶
func SanitizeInput(input string, config *ValidationConfig) string
SanitizeInput sanitiza input removendo padrões perigosos
func SecurityHeadersMiddleware ¶
func SecurityHeadersMiddleware(config *SecurityHeadersConfig) fiber.Handler
SecurityHeadersMiddleware cria middleware de security headers
func SemanticizeFilterQuery ¶
func SemanticizeFilterQuery( filter *GoDataFilterQuery, metadata EntityMetadata, ) error
SemanticizeFilterQuery adiciona informações semânticas à query de filtro baseado no contexto do serviço e entidade
func SetSkipValue ¶
func SetSkipValue(skip *GoDataSkipQuery, value int) error
SetSkipValue define o valor de $skip
func SetTopValue ¶
func SetTopValue(top *GoDataTopQuery, value int) error
SetTopValue define o valor de $top
func TenantBasedKeyGenerator ¶
TenantBasedKeyGenerator gera chave baseada no tenant (para multi-tenant)
func UserBasedKeyGenerator ¶
UserBasedKeyGenerator gera chave baseada no usuário autenticado
func ValidateCountLimit ¶
ValidateCountLimit valida se o count está dentro dos limites permitidos
func ValidateCountParameter ¶
ValidateCountParameter valida o parâmetro $count em uma URL
func ValidateCountValue ¶
ValidateCountValue valida se o valor do count é válido
func ValidateExpandDepth ¶
func ValidateExpandDepth(expand []ExpandOption, maxDepth int, currentDepth int) error
ValidateExpandDepth valida profundidade de $expand
func ValidateExpandItem ¶
func ValidateExpandItem(item *ExpandItem, service *EntityService, entity *EntityMetadata) error
ValidateExpandItem valida um item de expansão
func ValidateExpandQuery ¶
func ValidateExpandQuery(expand *GoDataExpandQuery, service *EntityService, entity *EntityMetadata) error
ValidateExpandQuery valida uma query de expansão contra metadados
func ValidateFilterExpression ¶
func ValidateFilterExpression(ctx context.Context, filter string, metadata EntityMetadata) error
ValidateFilterExpression valida uma expressão de filtro
func ValidateFilterQuery ¶
func ValidateFilterQuery(filter string, config *ValidationConfig) error
ValidateFilterQuery valida query string de $filter
func ValidateJWT ¶
ValidateJWT valida um token JWT (função standalone)
func ValidateOrderByQuery ¶
func ValidateOrderByQuery(orderBy string, config *ValidationConfig) error
ValidateOrderByQuery valida query string de $orderby
func ValidatePropertyName ¶
func ValidatePropertyName(name string, config *ValidationConfig) error
ValidatePropertyName valida nome de propriedade
func ValidateQueryOptions ¶
func ValidateQueryOptions(options *QueryOptions, config *ValidationConfig) error
ValidateQueryOptions valida todas as opções de query OData
func ValidateSearchQuery ¶
func ValidateSearchQuery(search string, config *ValidationConfig) error
ValidateSearchQuery valida query string de $search
func ValidateSelectProperty ¶
func ValidateSelectProperty(propertyName string, entity *EntityMetadata) error
ValidateSelectProperty valida se uma propriedade pode ser selecionada
func ValidateSelectQuery ¶
func ValidateSelectQuery(sel *GoDataSelectQuery, service *EntityService, entity *EntityMetadata) error
ValidateSelectQuery valida uma query de seleção contra metadados
func ValidateSelectString ¶
func ValidateSelectString(selectStr string, config *ValidationConfig) error
ValidateSelectString valida query string de $select
func ValidateSkipQuery ¶
func ValidateSkipQuery(skip *GoDataSkipQuery) error
ValidateSkipQuery valida uma query de $skip
func ValidateSkipValue ¶
ValidateSkipValue valida valor de $skip
func ValidateTopQuery ¶
func ValidateTopQuery(top *GoDataTopQuery) error
ValidateTopQuery valida uma query de $top
func ValidateTopSkipCombination ¶
func ValidateTopSkipCombination(top *GoDataTopQuery, skip *GoDataSkipQuery) error
ValidateTopSkipCombination valida a combinação de $top e $skip
func ValidateTopValue ¶
func ValidateTopValue(top int, config *ValidationConfig) error
ValidateTopValue valida valor de $top
Types ¶
type AssociationMetadata ¶
type AssociationMetadata struct {
ForeignKey string // Nome da chave estrangeira
References string // Campo referenciado na entidade relacionada
RelatedEntity string // Nome da entidade relacionada
CascadeFlags []string // SaveUpdate, Remove, Refresh
}
AssociationMetadata representa os metadados de uma associação simples (1:1 ou N:1)
type Associativity ¶
type Associativity int
Associativity associatividade dos operadores
const ( AssocLeft Associativity = iota AssocRight )
type AuditLogConfig ¶
type AuditLogConfig struct {
// Habilita/desabilita audit logging
Enabled bool
// Tipo de logger: "file", "stdout", "stderr", "none"
LogType string
// Caminho do arquivo de log (quando LogType = "file")
FilePath string
// Formato do log: "json" ou "text"
Format string
// Buffer size para escrita assíncrona
BufferSize int
// Operações a serem logadas (se vazio, loga todas)
LoggedOperations []AuditOperation
// Incluir dados sensíveis no log (não recomendado em produção)
IncludeSensitiveData bool
}
AuditLogConfig configurações de audit logging
func DefaultAuditLogConfig ¶
func DefaultAuditLogConfig() *AuditLogConfig
DefaultAuditLogConfig retorna configuração padrão de audit logging
type AuditLogEntry ¶
type AuditLogEntry struct {
Timestamp time.Time `json:"timestamp"`
UserID string `json:"user_id,omitempty"`
Username string `json:"username,omitempty"`
IP string `json:"ip"`
Method string `json:"method"`
Path string `json:"path"`
EntityName string `json:"entity_name,omitempty"`
Operation AuditOperation `json:"operation"`
EntityID string `json:"entity_id,omitempty"`
Success bool `json:"success"`
ErrorMessage string `json:"error_message,omitempty"`
Duration int64 `json:"duration_ms,omitempty"` // duração em milissegundos
UserAgent string `json:"user_agent,omitempty"`
RequestID string `json:"request_id,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
Extra map[string]interface{} `json:"extra,omitempty"`
}
AuditLogEntry representa uma entrada de audit log
type AuditLogger ¶
type AuditLogger interface {
Log(entry AuditLogEntry) error
Close() error
}
AuditLogger interface para audit logging
func NewAuditLogger ¶
func NewAuditLogger(config *AuditLogConfig) (AuditLogger, error)
NewAuditLogger cria uma nova instância de AuditLogger baseado na configuração
type AuditOperation ¶
type AuditOperation string
AuditOperation representa o tipo de operação auditada
const ( AuditOpCreate AuditOperation = "CREATE" AuditOpUpdate AuditOperation = "UPDATE" AuditOpDelete AuditOperation = "DELETE" AuditOpRead AuditOperation = "READ" AuditOpAuthSuccess AuditOperation = "AUTH_SUCCESS" AuditOpAuthFailure AuditOperation = "AUTH_FAILURE" AuditOpAuthLogout AuditOperation = "AUTH_LOGOUT" )
type BaseEntityService ¶
type BaseEntityService struct {
// contains filtered or unexported fields
}
BaseEntityService implementa o serviço base para entidades
func NewBaseEntityService ¶
func NewBaseEntityService(provider DatabaseProvider, metadata EntityMetadata, server *Server) *BaseEntityService
NewBaseEntityService cria uma nova instância do serviço base
func (*BaseEntityService) BuildTypedKeyFilter ¶
func (s *BaseEntityService) BuildTypedKeyFilter(ctx context.Context, keys map[string]any) (*GoDataFilterQuery, error)
BuildTypedKeyFilter constrói um filtro preservando os tipos das chaves
func (*BaseEntityService) GetComputeFields ¶
func (s *BaseEntityService) GetComputeFields(computeOption *ComputeOption) []PropertyMetadata
GetComputeFields retorna os campos computados como metadados
func (*BaseEntityService) GetCount ¶
func (s *BaseEntityService) GetCount(ctx context.Context, options QueryOptions) (int64, error)
GetCount retorna a contagem de registros que atendem às opções de consulta
func (*BaseEntityService) GetMetadata ¶
func (s *BaseEntityService) GetMetadata() EntityMetadata
GetMetadata retorna os metadados da entidade
func (*BaseEntityService) GetSearchableProperties ¶
func (s *BaseEntityService) GetSearchableProperties() []PropertyMetadata
GetSearchableProperties retorna as propriedades pesquisáveis da entidade
func (*BaseEntityService) ParseComputeQuery ¶
func (s *BaseEntityService) ParseComputeQuery(ctx context.Context, computeStr string) (*ComputeOption, error)
ParseComputeQuery analisa uma string $compute e retorna ComputeOption
func (*BaseEntityService) ParseSearchQuery ¶
func (s *BaseEntityService) ParseSearchQuery(ctx context.Context, searchStr string) (*SearchOption, error)
ParseSearchQuery analisa uma string $search e retorna SearchOption
func (*BaseEntityService) Patch ¶ added in v1.0.13
func (s *BaseEntityService) Patch(ctx context.Context, keys map[string]any, entity any) (any, error)
Patch processa um PATCH com suporte a hierarquias aninhadas (INSERT/UPDATE/DELETE) Se não houver hierarquia, delega para Update existente para manter compatibilidade
func (*BaseEntityService) Query ¶
func (s *BaseEntityService) Query(ctx context.Context, options QueryOptions) (*ODataResponse, error)
Query executa uma consulta OData seguindo a ordem correta de execução das query options
type BaseEventArgs ¶
type BaseEventArgs struct {
Context *EventContext
EventType EventType
EntityName string
Entity interface{}
// contains filtered or unexported fields
}
BaseEventArgs implementa a funcionalidade comum para todos os eventos
func (*BaseEventArgs) CanCancel ¶
func (e *BaseEventArgs) CanCancel() bool
func (*BaseEventArgs) Cancel ¶
func (e *BaseEventArgs) Cancel(reason string)
func (*BaseEventArgs) GetCancelReason ¶
func (e *BaseEventArgs) GetCancelReason() string
func (*BaseEventArgs) GetContext ¶
func (e *BaseEventArgs) GetContext() *EventContext
func (*BaseEventArgs) GetEntity ¶
func (e *BaseEventArgs) GetEntity() interface{}
func (*BaseEventArgs) GetEntityName ¶
func (e *BaseEventArgs) GetEntityName() string
func (*BaseEventArgs) GetEventType ¶
func (e *BaseEventArgs) GetEventType() EventType
func (*BaseEventArgs) GetManager ¶
func (e *BaseEventArgs) GetManager() *ObjectManager
GetManager retorna ObjectManager para uso nos eventos
func (*BaseEventArgs) IsCanceled ¶
func (e *BaseEventArgs) IsCanceled() bool
func (*BaseEventArgs) Manager ¶
func (e *BaseEventArgs) Manager() *ObjectManager
Manager retorna ObjectManager para uso nos eventos
func (*BaseEventArgs) SetEntity ¶
func (e *BaseEventArgs) SetEntity(entity interface{})
type BaseProvider ¶
type BaseProvider struct {
// contains filtered or unexported fields
}
BaseProvider implementa funcionalidades comuns a todos os providers
func NewBaseProvider ¶
func NewBaseProvider(connection *sql.DB, driverName string) *BaseProvider
NewBaseProvider cria um novo BaseProvider
func (*BaseProvider) BuildLimitClause ¶
func (p *BaseProvider) BuildLimitClause(skip, top int) string
BuildLimitClause constrói a cláusula LIMIT baseada no skip e top OData
func (*BaseProvider) BuildOrderByClause ¶
func (p *BaseProvider) BuildOrderByClause(orderBy string, metadata EntityMetadata) (string, error)
BuildOrderByClause constrói a cláusula ORDER BY baseada no orderBy OData
func (*BaseProvider) BuildSelectClause ¶
func (p *BaseProvider) BuildSelectClause(selectFields []string, metadata EntityMetadata) (string, error)
BuildSelectClause constrói a cláusula SELECT baseada no select OData
func (*BaseProvider) BuildSelectQueryOptimized ¶
func (p *BaseProvider) BuildSelectQueryOptimized(ctx context.Context, metadata EntityMetadata, options QueryOptions) (string, []interface{}, error)
BuildSelectQueryOptimized constrói query SELECT otimizada usando o novo query builder
func (*BaseProvider) BuildWhereClause ¶
func (p *BaseProvider) BuildWhereClause(filter string, metadata EntityMetadata) (string, []interface{}, error)
BuildWhereClause constrói a cláusula WHERE baseada no filtro OData (método legado)
func (*BaseProvider) ConvertValue ¶
func (p *BaseProvider) ConvertValue(value interface{}, targetType string) (interface{}, error)
ConvertValue converte um valor para o tipo apropriado
func (*BaseProvider) FormatDateTime ¶
func (p *BaseProvider) FormatDateTime(t time.Time) string
FormatDateTime formata uma data/hora para SQL
func (*BaseProvider) GetConnection ¶
func (p *BaseProvider) GetConnection() *sql.DB
GetConnection retorna a conexão com o banco
func (*BaseProvider) GetDriverName ¶
func (p *BaseProvider) GetDriverName() string
GetDriverName retorna o nome do driver
func (*BaseProvider) GetQueryBuilder ¶
func (p *BaseProvider) GetQueryBuilder() *QueryBuilder
GetQueryBuilder retorna o query builder, inicializando se necessário
func (*BaseProvider) InitParsers ¶
func (p *BaseProvider) InitParsers()
InitParsers inicializa os parsers de compute e search
func (*BaseProvider) InitQueryBuilder ¶
func (p *BaseProvider) InitQueryBuilder()
InitQueryBuilder inicializa o query builder
func (*BaseProvider) MapGoTypeToSQL ¶
func (p *BaseProvider) MapGoTypeToSQL(goType string) string
MapGoTypeToSQL mapeia tipos Go para tipos SQL genéricos
type BasicAuthConfig ¶
BasicAuthConfig configurações para Basic Auth
type BatchConfig ¶
type BatchConfig struct {
MaxOperations int // Máximo de operações por batch
MaxChangesets int // Máximo de changesets por batch
Timeout time.Duration // Timeout para execução do batch
EnableTransactions bool // Habilitar transações para changesets
}
BatchConfig configurações para batch requests
func DefaultBatchConfig ¶
func DefaultBatchConfig() *BatchConfig
DefaultBatchConfig retorna configuração padrão
type BatchHTTPOperation ¶
type BatchHTTPOperation struct {
Method string
URL string
Headers map[string]string
Body []byte
ContentID string // Para referências dentro do batch
}
BatchHTTPOperation representa uma operação HTTP individual no batch
type BatchOperation ¶
type BatchOperation struct {
Type string // "INSERT", "UPDATE", "DELETE"
Entity any
Key string
Data map[string]any
SQL string
Args []any
}
BatchOperation representa uma operação em lote
type BatchOperationResponse ¶
type BatchOperationResponse struct {
StatusCode int
Headers map[string]string
Body []byte
ContentID string
}
BatchOperationResponse representa a resposta de uma operação
type BatchPart ¶
type BatchPart struct {
IsChangeset bool
Request *BatchHTTPOperation
Changeset []*BatchHTTPOperation
}
BatchPart representa uma parte individual do batch (request ou changeset)
type BatchProcessor ¶
type BatchProcessor struct {
// contains filtered or unexported fields
}
BatchProcessor processa requisições batch
func NewBatchProcessor ¶
func NewBatchProcessor(server *Server) *BatchProcessor
NewBatchProcessor cria um novo processador de batch
func (*BatchProcessor) ExecuteBatch ¶
func (bp *BatchProcessor) ExecuteBatch(ctx context.Context, batchReq *BatchRequest) (*BatchResponse, error)
ExecuteBatch executa um batch request
func (*BatchProcessor) ParseBatchRequest ¶
func (bp *BatchProcessor) ParseBatchRequest(c fiber.Ctx) (*BatchRequest, error)
ParseBatchRequest faz o parsing de uma requisição batch multipart/mixed
func (*BatchProcessor) WriteBatchResponse ¶
func (bp *BatchProcessor) WriteBatchResponse(c fiber.Ctx, batchResp *BatchResponse) error
WriteBatchResponse escreve a resposta batch no formato multipart/mixed
type BatchRequest ¶
type BatchRequest struct {
Parts []*BatchPart
}
BatchRequest representa uma requisição batch OData
type BatchResponse ¶
type BatchResponse struct {
Parts []*BatchResponsePart
}
BatchResponse representa a resposta de um batch
type BatchResponsePart ¶
type BatchResponsePart struct {
IsChangeset bool
Response *BatchOperationResponse
Changeset []*BatchOperationResponse
}
BatchResponsePart representa uma parte da resposta
type Bool ¶
Bool representa um bool que pode ser null
func (Bool) MarshalJSON ¶
MarshalJSON implementa json.Marshaler
func (*Bool) UnmarshalJSON ¶
UnmarshalJSON implementa json.Unmarshaler
type ClientLimiter ¶
type ClientLimiter struct {
// contains filtered or unexported fields
}
ClientLimiter representa o limitador para um cliente específico
type ComplianceConfig ¶
type ComplianceConfig int
ComplianceConfig define configurações de compliance OData
const ( ComplianceStrict ComplianceConfig = iota ComplianceIgnoreUnknownKeywords ComplianceIgnoreDuplicateKeywords )
type ComputeExpression ¶
type ComputeExpression struct {
Expression string // A expressão a ser computada (ex: "Price mul Quantity")
Alias string // O alias para o resultado (ex: "Total")
ParseTree *ParseNode // Árvore de parse da expressão
}
ComputeExpression representa uma expressão de compute
type ComputeItem ¶
ComputeItem representa um item de compute (placeholder)
type ComputeOption ¶
type ComputeOption struct {
Expressions []ComputeExpression
}
ComputeOption representa todas as expressões de compute
type ComputeParser ¶
type ComputeParser struct {
// contains filtered or unexported fields
}
ComputeParser parser para expressões $compute
func NewComputeParser ¶
func NewComputeParser() *ComputeParser
NewComputeParser cria um novo parser de compute
func (*ComputeParser) GetComputeFields ¶
func (p *ComputeParser) GetComputeFields(computeOption *ComputeOption) []PropertyMetadata
GetComputeFields retorna os campos computados como metadados de propriedade
func (*ComputeParser) ParseCompute ¶
func (p *ComputeParser) ParseCompute(ctx context.Context, computeStr string) (*ComputeOption, error)
ParseCompute analisa uma string $compute
func (*ComputeParser) ValidateComputeExpression ¶
func (p *ComputeParser) ValidateComputeExpression(expr ComputeExpression, metadata EntityMetadata) error
ValidateComputeExpression valida uma expressão de compute contra metadados
type ComputeTokenType ¶
type ComputeTokenType int
ComputeTokenType representa tipos de tokens para $compute
const ( ComputeTokenProperty ComputeTokenType = iota ComputeTokenFunction ComputeTokenOperator ComputeTokenString ComputeTokenNumber ComputeTokenOpenParen ComputeTokenCloseParen ComputeTokenComma ComputeTokenAs ComputeTokenAlias ComputeTokenWhitespace )
func (ComputeTokenType) Value ¶
func (c ComputeTokenType) Value() int
type ConnectionConfig ¶
type ConnectionConfig struct {
Driver string
ConnectionString string
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
}
ConnectionConfig representa a configuração de conexão
type DatabaseProvider ¶
type DatabaseProvider interface {
Connect(connectionString string) error
Close() error
GetConnection() *sql.DB
GetDriverName() string
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
BuildSelectQuery(entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
BuildInsertQuery(entity EntityMetadata, data map[string]interface{}) (string, []interface{}, error)
BuildUpdateQuery(entity EntityMetadata, data map[string]interface{}, keyValues map[string]interface{}) (string, []interface{}, error)
BuildDeleteQuery(entity EntityMetadata, keyValues map[string]interface{}) (string, []interface{}, error)
BuildWhereClause(filter string, metadata EntityMetadata) (string, []interface{}, error)
BuildOrderByClause(orderBy string, metadata EntityMetadata) (string, error)
MapGoTypeToSQL(goType string) string
FormatDateTime(t time.Time) string
}
DatabaseProvider interface para os providers de banco
func GetProvider ¶
func GetProvider(c fiber.Ctx) DatabaseProvider
GetProvider retorna o DatabaseProvider do fiber context
type DefaultDialect ¶
type DefaultDialect struct{}
DefaultDialect implementa SQLDialect para bancos genéricos
func (*DefaultDialect) BuildCeilingFunction ¶
func (d *DefaultDialect) BuildCeilingFunction(arg string) string
BuildCeilingFunction constrói função CEILING
func (*DefaultDialect) BuildConcatFunction ¶
func (d *DefaultDialect) BuildConcatFunction(args []string) string
BuildConcatFunction constrói função CONCAT
func (*DefaultDialect) BuildDateExtractFunction ¶
func (d *DefaultDialect) BuildDateExtractFunction(functionName, arg string) string
BuildDateExtractFunction constrói função de extração de data
func (*DefaultDialect) BuildFullTextPhraseCondition ¶
func (d *DefaultDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
BuildFullTextPhraseCondition constrói condição genérica de full-text phrase search
func (*DefaultDialect) BuildFullTextSearchCondition ¶
func (d *DefaultDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
BuildFullTextSearchCondition constrói condição genérica de full-text search
func (*DefaultDialect) BuildLimitClause ¶
func (d *DefaultDialect) BuildLimitClause(top, skip int) string
BuildLimitClause constrói cláusula LIMIT/OFFSET genérica
func (*DefaultDialect) BuildNowFunction ¶
func (d *DefaultDialect) BuildNowFunction() string
BuildNowFunction constrói função NOW
func (*DefaultDialect) BuildSubstringFromFunction ¶
func (d *DefaultDialect) BuildSubstringFromFunction(str, start string) string
BuildSubstringFromFunction constrói SUBSTRING sem length
func (*DefaultDialect) BuildSubstringFunction ¶
func (d *DefaultDialect) BuildSubstringFunction(str, start, length string) string
BuildSubstringFunction constrói função SUBSTRING
func (*DefaultDialect) FormatDateTime ¶
func (d *DefaultDialect) FormatDateTime(t time.Time) string
FormatDateTime formata um time.Time de forma genérica
func (*DefaultDialect) GetName ¶
func (d *DefaultDialect) GetName() string
GetName retorna o nome do dialeto
func (*DefaultDialect) QuoteIdentifier ¶
func (d *DefaultDialect) QuoteIdentifier(identifier string) string
QuoteIdentifier retorna identificador sem quotes (comportamento padrão)
func (*DefaultDialect) SetupNodeMap ¶
func (d *DefaultDialect) SetupNodeMap() NodeMap
SetupNodeMap configura o mapa de operadores OData para SQL
func (*DefaultDialect) SetupPrepareMap ¶
func (d *DefaultDialect) SetupPrepareMap() PrepareMap
SetupPrepareMap configura o mapa de preparação de valores
func (*DefaultDialect) SupportsFullTextSearch ¶
func (d *DefaultDialect) SupportsFullTextSearch() bool
SupportsFullTextSearch indica que o banco genérico não suporta full-text search
type EntityAuthConfig ¶
type EntityAuthConfig struct {
RequireAuth bool // Se true, todas as operações requerem autenticação
RequiredRoles []string // Roles necessárias para acessar a entidade
RequiredScopes []string // Scopes necessários para acessar a entidade
RequireAdmin bool // Se true, apenas administradores podem acessar
ReadOnly bool // Se true, apenas operações de leitura são permitidas
Middlewares []fiber.Handler // Middlewares customizados (ex: JWT, Basic Auth)
Permissions []string // Operações permitidas: GET, POST, PUT, DELETE, PATCH - vazio = todas
}
EntityAuthConfig configurações de autenticação por entidade
type EntityCacheItem ¶
EntityCacheItem representa um item no cache de entidades
type EntityConfig ¶
type EntityConfig struct {
Name string
Entity interface{}
Middlewares []fiber.Handler // Middlewares aplicados às rotas da entidade
ReadOnly bool
Permissions []string // GET, POST, PUT, DELETE, PATCH - se vazio, permite todos
}
EntityConfig configuração de uma entidade
type EntityContainerMetadata ¶
type EntityContainerMetadata struct {
Name string `json:"name"`
EntitySets []EntitySetMetadata `json:"entitySets"`
}
EntityContainerMetadata representa os metadados de um container de entidades
type EntityDeletedArgs ¶
type EntityDeletedArgs struct {
*BaseEventArgs
Keys map[string]interface{}
DeletedEntity interface{}
}
EntityDeletedArgs argumentos para evento OnEntityDeleted
func NewEntityDeletedArgs ¶
func NewEntityDeletedArgs(ctx *EventContext, keys map[string]interface{}, entity interface{}) *EntityDeletedArgs
NewEntityDeletedArgs cria argumentos para evento EntityDeleted
type EntityDeletingArgs ¶
type EntityDeletingArgs struct {
*BaseEventArgs
Keys map[string]interface{}
EntityToDelete interface{}
CascadeDelete bool
}
EntityDeletingArgs argumentos para evento OnEntityDeleting
func NewEntityDeletingArgs ¶
func NewEntityDeletingArgs(ctx *EventContext, keys map[string]interface{}, entity interface{}) *EntityDeletingArgs
NewEntityDeletingArgs cria argumentos para evento EntityDeleting
type EntityErrorArgs ¶
type EntityErrorArgs struct {
*BaseEventArgs
Error error
Operation string
StatusCode int
CanRecover bool
}
EntityErrorArgs argumentos para evento OnEntityError
func NewEntityErrorArgs ¶
func NewEntityErrorArgs(ctx *EventContext, err error, operation string, statusCode int) *EntityErrorArgs
NewEntityErrorArgs cria argumentos para evento EntityError
type EntityEventManager ¶
type EntityEventManager struct {
// contains filtered or unexported fields
}
EntityEventManager gerencia todos os eventos de entidade
func NewEntityEventManager ¶
func NewEntityEventManager(logger *log.Logger) *EntityEventManager
NewEntityEventManager cria um novo gerenciador de eventos
func (*EntityEventManager) Clear ¶
func (em *EntityEventManager) Clear()
Clear remove todos os handlers
func (*EntityEventManager) ClearEntity ¶
func (em *EntityEventManager) ClearEntity(entityName string)
ClearEntity remove todos os handlers de uma entidade específica
func (*EntityEventManager) Emit ¶
func (em *EntityEventManager) Emit(args EventArgs) error
Emit dispara um evento
func (*EntityEventManager) GetHandlerCount ¶
func (em *EntityEventManager) GetHandlerCount(eventType EventType, entityName string) int
GetHandlerCount retorna o número de handlers registrados
func (*EntityEventManager) ListSubscriptions ¶
func (em *EntityEventManager) ListSubscriptions() map[string]interface{}
ListSubscriptions lista todas as assinaturas de eventos
func (*EntityEventManager) Subscribe ¶
func (em *EntityEventManager) Subscribe(eventType EventType, entityName string, handler EventHandler)
Subscribe registra um handler para um evento específico de uma entidade
func (*EntityEventManager) SubscribeFunc ¶
func (em *EntityEventManager) SubscribeFunc(eventType EventType, entityName string, handler func(args EventArgs) error)
SubscribeFunc registra uma função como handler
func (*EntityEventManager) SubscribeGlobal ¶
func (em *EntityEventManager) SubscribeGlobal(eventType EventType, handler EventHandler)
SubscribeGlobal registra um handler global para um tipo de evento
func (*EntityEventManager) SubscribeGlobalFunc ¶
func (em *EntityEventManager) SubscribeGlobalFunc(eventType EventType, handler func(args EventArgs) error)
SubscribeGlobalFunc registra uma função como handler global
type EntityGetArgs ¶
type EntityGetArgs struct {
*BaseEventArgs
Keys map[string]interface{}
QueryParams map[string]interface{}
}
EntityGetArgs argumentos para evento OnEntityGet
func NewEntityGetArgs ¶
func NewEntityGetArgs(ctx *EventContext, keys map[string]interface{}, entity interface{}) *EntityGetArgs
NewEntityGetArgs cria argumentos para evento EntityGet
type EntityInsertedArgs ¶
type EntityInsertedArgs struct {
*BaseEventArgs
CreatedEntity interface{}
NewID interface{}
}
EntityInsertedArgs argumentos para evento OnEntityInserted
func NewEntityInsertedArgs ¶
func NewEntityInsertedArgs(ctx *EventContext, entity interface{}) *EntityInsertedArgs
NewEntityInsertedArgs cria argumentos para evento EntityInserted
type EntityInsertingArgs ¶
type EntityInsertingArgs struct {
*BaseEventArgs
Data map[string]interface{}
ValidationErrors []string
}
EntityInsertingArgs argumentos para evento OnEntityInserting
func NewEntityInsertingArgs ¶
func NewEntityInsertingArgs(ctx *EventContext, data map[string]interface{}) *EntityInsertingArgs
NewEntityInsertingArgs cria argumentos para evento EntityInserting
type EntityListArgs ¶
type EntityListArgs struct {
*BaseEventArgs
QueryOptions QueryOptions
Results []interface{}
TotalCount int64
FilterApplied bool
CustomFilters map[string]interface{}
}
EntityListArgs argumentos para evento OnEntityList
func NewEntityListArgs ¶
func NewEntityListArgs(ctx *EventContext, options QueryOptions, results []interface{}) *EntityListArgs
NewEntityListArgs cria argumentos para evento EntityList
type EntityMapper ¶
type EntityMapper struct{}
EntityMapper é responsável por mapear structs para metadados OData
func NewEntityMapper ¶
func NewEntityMapper() *EntityMapper
NewEntityMapper cria uma nova instância do mapper
func (*EntityMapper) MapEntity ¶
func (m *EntityMapper) MapEntity(entity interface{}) (EntityMetadata, error)
MapEntity mapeia uma struct para EntityMetadata usando tags
type EntityMetadata ¶
type EntityMetadata struct {
Name string
TableName string
Schema string // Schema da tabela
Properties []PropertyMetadata
Keys []string
}
EntityMetadata representa os metadados de uma entidade
func MapEntityFromStruct ¶
func MapEntityFromStruct(entity interface{}) (EntityMetadata, error)
MapEntityFromStruct é uma função helper para mapear rapidamente uma struct
type EntityModifiedArgs ¶
type EntityModifiedArgs struct {
*BaseEventArgs
Keys map[string]interface{}
UpdatedEntity interface{}
OriginalEntity interface{}
ModifiedFields []string
}
EntityModifiedArgs argumentos para evento OnEntityModified
func NewEntityModifiedArgs ¶
func NewEntityModifiedArgs(ctx *EventContext, keys map[string]interface{}, updated, original interface{}) *EntityModifiedArgs
NewEntityModifiedArgs cria argumentos para evento EntityModified
type EntityModifyingArgs ¶
type EntityModifyingArgs struct {
*BaseEventArgs
Keys map[string]interface{}
Data map[string]interface{}
OriginalEntity interface{}
ValidationErrors []string
}
EntityModifyingArgs argumentos para evento OnEntityModifying
func NewEntityModifyingArgs ¶
func NewEntityModifyingArgs(ctx *EventContext, keys map[string]interface{}, data map[string]interface{}, original interface{}) *EntityModifyingArgs
NewEntityModifyingArgs cria argumentos para evento EntityModifying
type EntityOption ¶
type EntityOption func(*EntityConfig)
EntityOption função que modifica a configuração de uma entidade
func WithMiddleware ¶
func WithMiddleware(middlewares ...fiber.Handler) EntityOption
WithMiddleware adiciona middlewares à entidade (ex: JWT, Basic Auth, etc)
func WithPermissions ¶
func WithPermissions(permissions ...string) EntityOption
WithPermissions define quais operações HTTP são permitidas na entidade Exemplo: WithPermissions("GET", "POST") - permite apenas GET e POST Se não especificado, permite todas as operações
func WithReadOnly ¶
func WithReadOnly(readOnly bool) EntityOption
WithReadOnly configura uma entidade como somente leitura
type EntityService ¶
type EntityService interface {
GetMetadata() EntityMetadata
Query(ctx context.Context, options QueryOptions) (*ODataResponse, error)
Get(ctx context.Context, keys map[string]interface{}) (interface{}, error)
Create(ctx context.Context, entity interface{}) (interface{}, error)
Update(ctx context.Context, keys map[string]interface{}, entity interface{}) (interface{}, error)
Delete(ctx context.Context, keys map[string]interface{}) error
}
EntityService interface para serviços de entidade
type EntitySetMetadata ¶
type EntitySetMetadata struct {
Name string `json:"name"`
EntityType string `json:"entityType"`
Kind string `json:"kind"`
URL string `json:"url"`
}
EntitySetMetadata representa os metadados de um conjunto de entidades
type EntityTypeMetadata ¶
type EntityTypeMetadata struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Keys []string `json:"keys"`
Properties []PropertyTypeMetadata `json:"properties"`
}
EntityTypeMetadata representa os metadados de um tipo de entidade
type EntityValidatedArgs ¶
type EntityValidatedArgs struct {
*BaseEventArgs
Data map[string]interface{}
ValidationErrors []string
IsValid bool
}
EntityValidatedArgs argumentos para evento OnEntityValidated
type EntityValidatingArgs ¶
type EntityValidatingArgs struct {
*BaseEventArgs
Data map[string]interface{}
ValidationErrors []string
}
EntityValidatingArgs argumentos para evento OnEntityValidating
type EnvConfig ¶
type EnvConfig struct {
// Configurações do banco de dados
DBDriver string
DBHost string
DBPort string
DBName string
DBUser string
DBPassword string
DBSchema string
DBConnectionString string
DBMaxOpenConns int
DBMaxIdleConns int
DBConnMaxLifetime time.Duration
DBConnMaxIdleTime time.Duration
DBLogSQL bool // Habilita/desabilita logs de queries SQL
LogPayloads bool // Habilita/desabilita logs de payloads de request/response
// Configurações do servidor OData
ServerHost string
ServerPort int
ServerRoutePrefix string
ServerEnableCORS bool
ServerAllowedOrigins []string
ServerAllowedMethods []string
ServerAllowedHeaders []string
ServerExposedHeaders []string
ServerAllowCredentials bool
ServerEnableLogging bool
ServerLogLevel string
ServerLogFile string
ServerEnableCompression bool
ServerMaxRequestSize int64
ServerShutdownTimeout time.Duration
// Configurações TLS
ServerTLSCertFile string
ServerTLSKeyFile string
// Configurações JWT
JWTSecretKey string
JWTIssuer string
JWTExpiresIn time.Duration
JWTRefreshIn time.Duration
JWTAlgorithm string
JWTEnabled bool
JWTRequireAuth bool
// Configurações do serviço
ServiceName string
ServiceDisplayName string
ServiceDescription string
// Configurações de Rate Limit
RateLimitEnabled bool
RateLimitRequestsPerMinute int
RateLimitBurstSize int
RateLimitWindowSize time.Duration
RateLimitHeaders bool
// Configurações de PATCH OData 4.01
PatchRemovedFormat string // Formato aceito para @odata.removed: "both", "empty", "with_reason" (default: "both")
// Mapa de todas as variáveis para acesso direto
Variables map[string]string
}
EnvConfig representa as configurações carregadas do arquivo .env
func LoadEnvConfig ¶
LoadEnvConfig carrega configurações do arquivo .env
func LoadEnvOrDefault ¶
LoadEnvOrDefault carrega configurações do .env ou retorna configurações padrão
func (*EnvConfig) BuildConnectionString ¶
BuildConnectionString constrói a string de conexão baseada nas configurações
func (*EnvConfig) CreateProviderFromConfig ¶
func (c *EnvConfig) CreateProviderFromConfig() DatabaseProvider
CreateProviderFromConfig cria um provider baseado no config (singleton por connectionString)
func (*EnvConfig) PrintLoadedConfig ¶
func (c *EnvConfig) PrintLoadedConfig()
PrintLoadedConfig imprime as configurações carregadas para debug
func (*EnvConfig) ToServerConfig ¶
func (c *EnvConfig) ToServerConfig() *ServerConfig
ToServerConfig converte a configuração .env para ServerConfig
type EventArgs ¶
type EventArgs interface {
GetContext() *EventContext
GetEventType() EventType
GetEntityName() string
GetEntity() interface{}
SetEntity(interface{})
CanCancel() bool
Cancel(reason string)
IsCanceled() bool
GetCancelReason() string
Manager() *ObjectManager
GetManager() *ObjectManager
}
EventArgs é a interface base para todos os argumentos de evento
type EventContext ¶
type EventContext struct {
Context context.Context
FiberContext fiber.Ctx
EntityName string
EntityType string
UserID string
UserRoles []string
UserScopes []string
RequestID string
Timestamp int64
Extra map[string]interface{}
DatabaseProvider DatabaseProvider // Para acesso direto ao provider
}
EventContext contém informações contextuais sobre o evento
type EventHandler ¶
EventHandler representa um handler de evento
type EventHandlerFunc ¶
EventHandlerFunc é uma função que pode ser usada como handler
func (EventHandlerFunc) Handle ¶
func (f EventHandlerFunc) Handle(args EventArgs) error
Implementa a interface EventHandler
type EventType ¶
type EventType string
EventType representa os tipos de eventos disponíveis
const ( // Eventos de recuperação de dados EventEntityGet EventType = "EntityGet" EventEntityList EventType = "EntityList" // Eventos de inserção (antes e depois) EventEntityInserting EventType = "EntityInserting" EventEntityInserted EventType = "EntityInserted" // Eventos de atualização (antes e depois) EventEntityModifying EventType = "EntityModifying" EventEntityModified EventType = "EntityModified" // Eventos de exclusão (antes e depois) EventEntityDeleting EventType = "EntityDeleting" EventEntityDeleted EventType = "EntityDeleted" // Eventos de validação EventEntityValidating EventType = "EntityValidating" EventEntityValidated EventType = "EntityValidated" // Eventos de exceção EventEntityError EventType = "EntityError" )
type ExpandItem ¶
type ExpandItem struct {
Path []*Token
Filter *GoDataFilterQuery
At *GoDataFilterQuery
Search *GoDataSearchQuery
OrderBy *GoDataOrderByQuery
Skip *GoDataSkipQuery
Top *GoDataTopQuery
Select *GoDataSelectQuery
Compute *GoDataComputeQuery
Expand *GoDataExpandQuery
Levels int
}
ExpandItem representa um item individual de expansão
func ParseExpandItem ¶
func ParseExpandItem(ctx context.Context, input *TokenQueue) (*ExpandItem, error)
ParseExpandItem faz o parsing de um item individual de expansão
type ExpandOption ¶
type ExpandOption struct {
Property string // Nome da propriedade a ser expandida
Filter string // $filter aplicado à expansão
OrderBy string // $orderby aplicado à expansão
Select []string // $select aplicado à expansão
Expand []ExpandOption // $expand recursivo aplicado à expansão
Skip int // $skip aplicado à expansão
Top int // $top aplicado à expansão
Count bool // $count aplicado à expansão
}
ExpandOption representa uma opção de expansão com suas sub-opções
type ExpandTokenType ¶
type ExpandTokenType int
ExpandTokenType representa os tipos de tokens para parsing do $expand
const ( ExpandTokenOpenParen ExpandTokenType = iota ExpandTokenCloseParen ExpandTokenComma ExpandTokenSemicolon ExpandTokenEquals ExpandTokenLiteral )
func (ExpandTokenType) Value ¶
func (e ExpandTokenType) Value() int
type ExpressionParser ¶
type ExpressionParser struct {
// contains filtered or unexported fields
}
ExpressionParser parser para expressões OData
var GlobalFilterParser *ExpressionParser
Singleton global para filter parser
func GetGlobalExpressionParser ¶
func GetGlobalExpressionParser() *ExpressionParser
GetGlobalExpressionParser retorna instância singleton do expression parser
func NewExpressionParser ¶
func NewExpressionParser() *ExpressionParser
NewExpressionParser cria um novo parser de expressões
func (*ExpressionParser) ConvertToFilterExpressions ¶
func (p *ExpressionParser) ConvertToFilterExpressions(node *ParseNode) ([]FilterExpression, error)
ConvertToFilterExpressions converte árvore de parse para FilterExpression (compatibilidade)
func (*ExpressionParser) InfixToPostfix ¶
InfixToPostfix converte expressão infix para postfix usando algoritmo Shunting Yard otimizado
func (*ExpressionParser) ParseFilterExpression ¶
func (p *ExpressionParser) ParseFilterExpression(ctx context.Context, filter string) (*ParseNode, error)
ParseFilterExpression analisa uma expressão de filtro
func (*ExpressionParser) PostfixToTree ¶
PostfixToTree constrói árvore de parse a partir de expressão postfix
type FiberContextKeyType ¶
type FiberContextKeyType struct{}
FiberContextKeyType define um tipo customizado para chave do Fiber Context
type FileAuditLogger ¶
type FileAuditLogger struct {
// contains filtered or unexported fields
}
FileAuditLogger implementa AuditLogger escrevendo em arquivo
func NewFileAuditLogger ¶
func NewFileAuditLogger(config *AuditLogConfig) (*FileAuditLogger, error)
NewFileAuditLogger cria um novo FileAuditLogger
func (*FileAuditLogger) Close ¶
func (l *FileAuditLogger) Close() error
Close fecha o logger e aguarda escrita de buffer
func (*FileAuditLogger) Log ¶
func (l *FileAuditLogger) Log(entry AuditLogEntry) error
Log adiciona uma entrada ao log
type FilterExpression ¶
type FilterExpression struct {
Property string
Operator FilterOperator
Value interface{}
// Para funções que precisam de múltiplos argumentos
Arguments []interface{}
}
FilterExpression representa uma expressão de filtro
type FilterOperator ¶
type FilterOperator string
FilterOperator representa os operadores de filtro OData
const ( FilterEq FilterOperator = "eq" FilterNe FilterOperator = "ne" FilterGt FilterOperator = "gt" FilterGe FilterOperator = "ge" FilterLt FilterOperator = "lt" FilterLe FilterOperator = "le" FilterIn FilterOperator = "in" FilterContains FilterOperator = "contains" FilterStartsWith FilterOperator = "startswith" FilterEndsWith FilterOperator = "endswith" // Funções de string FilterLength FilterOperator = "length" FilterToLower FilterOperator = "tolower" FilterToUpper FilterOperator = "toupper" FilterTrim FilterOperator = "trim" FilterConcat FilterOperator = "concat" FilterIndexOf FilterOperator = "indexof" FilterSubstring FilterOperator = "substring" // Operadores matemáticos FilterAdd FilterOperator = "add" FilterSub FilterOperator = "sub" FilterMul FilterOperator = "mul" FilterDiv FilterOperator = "div" FilterMod FilterOperator = "mod" // Funções de data/hora FilterYear FilterOperator = "year" FilterMonth FilterOperator = "month" FilterDay FilterOperator = "day" FilterHour FilterOperator = "hour" FilterMinute FilterOperator = "minute" FilterSecond FilterOperator = "second" FilterNow FilterOperator = "now" )
type FilterTokenType ¶
type FilterTokenType int
FilterTokenType representa os tipos de tokens para filtros
const ( FilterTokenProperty FilterTokenType = iota + 1 FilterTokenFunction FilterTokenArithmetic FilterTokenString FilterTokenNumber FilterTokenOpenParen FilterTokenCloseParen FilterTokenComma FilterTokenLogical FilterTokenComparison FilterTokenBoolean FilterTokenNull FilterTokenDateTime FilterTokenDate FilterTokenTime FilterTokenGuid FilterTokenDuration FilterTokenGeographyPoint FilterTokenGeometryPoint )
type Float64 ¶
Float64 representa um float64 que pode ser null
func (Float64) MarshalJSON ¶
MarshalJSON implementa json.Marshaler
func (*Float64) UnmarshalJSON ¶
UnmarshalJSON implementa json.Unmarshaler
type GoDataComputeQuery ¶
type GoDataComputeQuery struct {
ComputeItems []*ComputeItem
RawValue string
}
GoDataComputeQuery representa uma query de compute OData (placeholder)
func ParseComputeString ¶
func ParseComputeString(ctx context.Context, compute string) (*GoDataComputeQuery, error)
type GoDataCountQuery ¶
type GoDataCountQuery bool
GoDataCountQuery representa uma query de count processada Seguindo o padrão do goDataCisco, count é um boolean simples
func OptimizeCountQuery ¶
func OptimizeCountQuery(count *GoDataCountQuery) *GoDataCountQuery
OptimizeCountQuery otimiza uma query de count
func ParseCountParameter ¶
func ParseCountParameter(params map[string]string) (*GoDataCountQuery, error)
ParseCountParameter é uma função auxiliar para parsing de parâmetros de URL
func ParseCountString ¶
func ParseCountString(count string) (*GoDataCountQuery, error)
ParseCountString converte uma string do parâmetro $count da URL em um boolean que indica se o count deve ser incluído na resposta.
func SetCountValue ¶
func SetCountValue(value bool) *GoDataCountQuery
SetCountValue define o valor do count
func (*GoDataCountQuery) MarshalJSON ¶
func (c *GoDataCountQuery) MarshalJSON() ([]byte, error)
MarshalJSON implementa json.Marshaler
func (*GoDataCountQuery) String ¶
func (c *GoDataCountQuery) String() string
String retorna a representação string do count
func (*GoDataCountQuery) UnmarshalJSON ¶
func (c *GoDataCountQuery) UnmarshalJSON(data []byte) error
UnmarshalJSON implementa json.Unmarshaler
type GoDataExpandQuery ¶
type GoDataExpandQuery struct {
ExpandItems []*ExpandItem
RawValue string
}
GoDataExpandQuery representa uma query de expansão OData
func ParseExpandString ¶
func ParseExpandString(ctx context.Context, expand string) (*GoDataExpandQuery, error)
ParseExpandString faz o parsing de uma string de $expand
func (*GoDataExpandQuery) String ¶
func (e *GoDataExpandQuery) String() string
String retorna a representação em string da query de expansão
type GoDataFilterQuery ¶
GoDataFilterQuery representa uma query de filtro processada
func OptimizeFilterExpression ¶
func OptimizeFilterExpression(filter *GoDataFilterQuery) *GoDataFilterQuery
OptimizeFilterExpression otimiza uma expressão de filtro removendo redundâncias
func ParseFilterString ¶
func ParseFilterString(ctx context.Context, filter string) (*GoDataFilterQuery, error)
ParseFilterString converte uma string do parâmetro $filter da URL em uma árvore de parse que pode ser usada por providers para criar uma resposta.
type GoDataOrderByQuery ¶
type GoDataOrderByQuery struct {
OrderByItems []*OrderByItem
RawValue string
}
GoDataOrderByQuery representa uma query de ordenação OData (placeholder)
func ParseOrderByString ¶
func ParseOrderByString(ctx context.Context, orderBy string) (*GoDataOrderByQuery, error)
type GoDataSearchQuery ¶
GoDataSearchQuery representa uma query de busca OData (placeholder)
func ParseSearchString ¶
func ParseSearchString(ctx context.Context, search string) (*GoDataSearchQuery, error)
Funções placeholder para parsers que ainda não foram implementados
func (*GoDataSearchQuery) GetTerms ¶
func (q *GoDataSearchQuery) GetTerms() []string
GetTerms extrai todos os termos de busca da query
func (*GoDataSearchQuery) Query ¶
func (q *GoDataSearchQuery) Query() string
Query retorna a query de busca original
func (*GoDataSearchQuery) String ¶
func (q *GoDataSearchQuery) String() string
String retorna a representação string da query
type GoDataSelectQuery ¶
type GoDataSelectQuery struct {
SelectItems []*SelectItem
RawValue string
}
GoDataSelectQuery representa uma query de seleção OData
func ParseSelectString ¶
func ParseSelectString(ctx context.Context, sel string) (*GoDataSelectQuery, error)
ParseSelectString faz o parsing de uma string de $select
func (*GoDataSelectQuery) AddSelectItem ¶
func (s *GoDataSelectQuery) AddSelectItem(propertyName string)
AddSelectItem adiciona um item de seleção
func (*GoDataSelectQuery) GetSelectItemByProperty ¶
func (s *GoDataSelectQuery) GetSelectItemByProperty(propertyName string) *SelectItem
GetSelectItemByProperty retorna o item de seleção para uma propriedade específica
func (*GoDataSelectQuery) HasProperty ¶
func (s *GoDataSelectQuery) HasProperty(propertyName string) bool
HasProperty verifica se uma propriedade específica está selecionada
func (*GoDataSelectQuery) RemoveSelectItem ¶
func (s *GoDataSelectQuery) RemoveSelectItem(propertyName string)
RemoveSelectItem remove um item de seleção
func (*GoDataSelectQuery) String ¶
func (s *GoDataSelectQuery) String() string
String retorna a representação em string da query de seleção
type GoDataSkipQuery ¶
type GoDataSkipQuery int
GoDataSkipQuery representa uma query de $skip OData
func ParseSkipString ¶
func ParseSkipString(ctx context.Context, skip string) (*GoDataSkipQuery, error)
ParseSkipString faz o parsing de uma string de $skip
func (*GoDataSkipQuery) String ¶
func (s *GoDataSkipQuery) String() string
String retorna a representação em string da query de $skip
type GoDataTopQuery ¶
type GoDataTopQuery int
GoDataTopQuery representa uma query de $top OData
func ParseTopString ¶
func ParseTopString(ctx context.Context, top string) (*GoDataTopQuery, error)
ParseTopString faz o parsing de uma string de $top
func (*GoDataTopQuery) String ¶
func (t *GoDataTopQuery) String() string
String retorna a representação em string da query de $top
type IDGeneratorType ¶
type IDGeneratorType string
IDGeneratorType representa os tipos de geradores de ID
const ( IDGeneratorNone IDGeneratorType = "none" IDGeneratorSequence IDGeneratorType = "sequence" IDGeneratorGuid IDGeneratorType = "guid" IDGeneratorUuid38 IDGeneratorType = "uuid38" IDGeneratorUuid36 IDGeneratorType = "uuid36" IDGeneratorUuid32 IDGeneratorType = "uuid32" IDGeneratorSmartGuid IDGeneratorType = "smartGuid" )
type Int64 ¶
Int64 representa um int64 que pode ser null
func (Int64) MarshalJSON ¶
MarshalJSON implementa json.Marshaler
func (*Int64) UnmarshalJSON ¶
UnmarshalJSON implementa json.Unmarshaler
type JWTConfig ¶
type JWTConfig struct {
SecretKey string
Issuer string
ExpiresIn time.Duration
RefreshIn time.Duration
Algorithm string
ContextKey string // Chave para armazenar o token no contexto (padrão: "user")
}
JWTConfig configurações para JWT
type ManyAssociationMetadata ¶
type ManyAssociationMetadata struct {
ForeignKey string // Nome da chave estrangeira
References string // Campo referenciado na entidade relacionada
RelatedEntity string // Nome da entidade relacionada
CascadeFlags []string // SaveUpdate, Remove, Refresh, RemoveOrphan
JoinTable string // Nome da tabela de junção (para N:N)
JoinColumn string // Coluna de junção (para N:N)
InverseJoinColumn string // Coluna de junção inversa (para N:N)
}
ManyAssociationMetadata representa os metadados de uma associação múltipla (1:N ou N:N)
type MetadataResponse ¶
type MetadataResponse struct {
Context string `json:"@odata.context"`
Version string `json:"@odata.version"`
Entities []EntityTypeMetadata `json:"entities"`
EntitySets []EntitySetMetadata `json:"entitySets"`
Schemas []SchemaMetadata `json:"schemas"`
}
MetadataResponse representa a resposta de metadados em JSON
type MultiTenantConfig ¶
type MultiTenantConfig struct {
Enabled bool
IdentificationMode string // header, subdomain, path, jwt
HeaderName string
DefaultTenant string
Tenants map[string]*TenantConfig
// Configurações globais herdadas
*EnvConfig
}
MultiTenantConfig representa configurações multi-tenant
func LoadMultiTenantConfig ¶
func LoadMultiTenantConfig() *MultiTenantConfig
LoadMultiTenantConfig carrega configurações multi-tenant automaticamente
func (*MultiTenantConfig) GetAllTenantIDs ¶
func (mtc *MultiTenantConfig) GetAllTenantIDs() []string
GetAllTenantIDs retorna lista de todos os tenant IDs
func (*MultiTenantConfig) GetTenantConfig ¶
func (mtc *MultiTenantConfig) GetTenantConfig(tenantID string) *TenantConfig
GetTenantConfig retorna configuração de um tenant específico
func (*MultiTenantConfig) PrintMultiTenantConfig ¶
func (mtc *MultiTenantConfig) PrintMultiTenantConfig()
PrintMultiTenantConfig imprime as configurações multi-tenant para debug
func (*MultiTenantConfig) TenantExists ¶
func (mtc *MultiTenantConfig) TenantExists(tenantID string) bool
TenantExists verifica se um tenant existe
type MultiTenantEntityService ¶
type MultiTenantEntityService struct {
*BaseEntityService
// contains filtered or unexported fields
}
MultiTenantEntityService encapsula o BaseEntityService com suporte multi-tenant
func NewMultiTenantEntityService ¶
func NewMultiTenantEntityService(metadata EntityMetadata, server *Server) *MultiTenantEntityService
NewMultiTenantEntityService cria um novo serviço multi-tenant
func (*MultiTenantEntityService) Create ¶
Create cria uma nova entidade usando o provider apropriado
func (*MultiTenantEntityService) ExecuteWithTenant ¶
func (s *MultiTenantEntityService) ExecuteWithTenant(tenantID string, operation func(provider DatabaseProvider) error) error
ExecuteWithTenant executa uma operação com um tenant específico
func (*MultiTenantEntityService) Get ¶
Get executa uma consulta de entidade específica usando o provider apropriado
func (*MultiTenantEntityService) GetAvailableTenants ¶
func (s *MultiTenantEntityService) GetAvailableTenants() []string
GetAvailableTenants retorna lista de tenants disponíveis
func (*MultiTenantEntityService) GetCurrentTenantFromContext ¶
func (s *MultiTenantEntityService) GetCurrentTenantFromContext(ctx context.Context) string
GetCurrentTenantFromContext extrai o tenant ID do contexto
func (*MultiTenantEntityService) GetTenantProvider ¶
func (s *MultiTenantEntityService) GetTenantProvider(tenantID string) DatabaseProvider
GetTenantProvider retorna o provider para um tenant específico
func (*MultiTenantEntityService) GetTenantStats ¶
func (s *MultiTenantEntityService) GetTenantStats(tenantID string) map[string]interface{}
GetTenantStats retorna estatísticas do tenant para esta entidade
func (*MultiTenantEntityService) IsMultiTenantEnabled ¶
func (s *MultiTenantEntityService) IsMultiTenantEnabled() bool
IsMultiTenantEnabled verifica se o multi-tenant está habilitado
func (*MultiTenantEntityService) LogMultiTenantInfo ¶
func (s *MultiTenantEntityService) LogMultiTenantInfo()
LogMultiTenantInfo registra informações sobre o estado multi-tenant
func (*MultiTenantEntityService) Query ¶
func (s *MultiTenantEntityService) Query(ctx context.Context, options QueryOptions) (*ODataResponse, error)
Query executa uma consulta usando o provider apropriado
func (*MultiTenantEntityService) Update ¶
func (s *MultiTenantEntityService) Update(ctx context.Context, keys map[string]any, entity any) (any, error)
Update atualiza uma entidade usando o provider apropriado
func (*MultiTenantEntityService) ValidateTenantAccess ¶
func (s *MultiTenantEntityService) ValidateTenantAccess(ctx context.Context, operation string) error
ValidateTenantAccess valida se o tenant pode acessar esta entidade
func (*MultiTenantEntityService) WithTenantContext ¶
func (s *MultiTenantEntityService) WithTenantContext(ctx context.Context, tenantID string) context.Context
WithTenantContext cria um novo contexto com tenant específico
type MultiTenantProviderPool ¶
type MultiTenantProviderPool struct {
// contains filtered or unexported fields
}
MultiTenantProviderPool gerencia pools de conexões para múltiplos tenants
func GetConnectionPool ¶
func GetConnectionPool(c fiber.Ctx) *MultiTenantProviderPool
GetConnectionPool retorna o pool multi-tenant
func NewMultiTenantProviderPool ¶
func NewMultiTenantProviderPool(config *MultiTenantConfig, logger *log.Logger) *MultiTenantProviderPool
NewMultiTenantProviderPool cria um novo pool multi-tenant
func (*MultiTenantProviderPool) AddTenant ¶
func (p *MultiTenantProviderPool) AddTenant(tenantID string, config *TenantConfig) error
AddTenant adiciona um novo tenant dinamicamente
func (*MultiTenantProviderPool) Close ¶
func (p *MultiTenantProviderPool) Close() error
Close fecha todas as conexões do pool
func (*MultiTenantProviderPool) GetAllStats ¶
func (p *MultiTenantProviderPool) GetAllStats() map[string]interface{}
GetAllStats retorna estatísticas de todos os tenants
func (*MultiTenantProviderPool) GetProvider ¶
func (p *MultiTenantProviderPool) GetProvider(tenantID string) DatabaseProvider
GetProvider retorna o provider para um tenant específico
func (*MultiTenantProviderPool) GetTenantList ¶
func (p *MultiTenantProviderPool) GetTenantList() []string
GetTenantList retorna lista de tenants disponíveis
func (*MultiTenantProviderPool) GetTenantStats ¶
func (p *MultiTenantProviderPool) GetTenantStats(tenantID string) map[string]interface{}
GetTenantStats retorna estatísticas de um tenant específico
func (*MultiTenantProviderPool) HealthCheck ¶
func (p *MultiTenantProviderPool) HealthCheck() map[string]interface{}
HealthCheck verifica a saúde de todas as conexões
func (*MultiTenantProviderPool) InitializeProviders ¶
func (p *MultiTenantProviderPool) InitializeProviders() error
InitializeProviders inicializa todos os providers configurados
func (*MultiTenantProviderPool) IsEnabled ¶
func (p *MultiTenantProviderPool) IsEnabled() bool
IsEnabled retorna se o modo multi-tenant está habilitado
func (*MultiTenantProviderPool) RemoveTenant ¶
func (p *MultiTenantProviderPool) RemoveTenant(tenantID string) error
RemoveTenant remove um tenant e fecha sua conexão
type MySQLDialect ¶
type MySQLDialect struct{}
MySQLDialect implementa SQLDialect para MySQL
func (*MySQLDialect) BuildCeilingFunction ¶
func (d *MySQLDialect) BuildCeilingFunction(arg string) string
BuildCeilingFunction constrói função CEILING para MySQL
func (*MySQLDialect) BuildConcatFunction ¶
func (d *MySQLDialect) BuildConcatFunction(args []string) string
BuildConcatFunction constrói função CONCAT para MySQL
func (*MySQLDialect) BuildDateExtractFunction ¶
func (d *MySQLDialect) BuildDateExtractFunction(functionName, arg string) string
BuildDateExtractFunction constrói função de extração de data para MySQL
func (*MySQLDialect) BuildFullTextPhraseCondition ¶
func (d *MySQLDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
BuildFullTextPhraseCondition constrói condição de full-text phrase search para MySQL
func (*MySQLDialect) BuildFullTextSearchCondition ¶
func (d *MySQLDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
BuildFullTextSearchCondition constrói condição de full-text search para MySQL
func (*MySQLDialect) BuildLimitClause ¶
func (d *MySQLDialect) BuildLimitClause(top, skip int) string
BuildLimitClause constrói cláusula LIMIT/OFFSET para MySQL
func (*MySQLDialect) BuildNowFunction ¶
func (d *MySQLDialect) BuildNowFunction() string
BuildNowFunction constrói função NOW para MySQL
func (*MySQLDialect) BuildSubstringFromFunction ¶
func (d *MySQLDialect) BuildSubstringFromFunction(str, start string) string
BuildSubstringFromFunction constrói SUBSTRING sem length para MySQL
func (*MySQLDialect) BuildSubstringFunction ¶
func (d *MySQLDialect) BuildSubstringFunction(str, start, length string) string
BuildSubstringFunction constrói função SUBSTRING para MySQL
func (*MySQLDialect) FormatDateTime ¶
func (d *MySQLDialect) FormatDateTime(t time.Time) string
FormatDateTime formata um time.Time para MySQL
func (*MySQLDialect) GetName ¶
func (d *MySQLDialect) GetName() string
GetName retorna o nome do dialeto
func (*MySQLDialect) QuoteIdentifier ¶
func (d *MySQLDialect) QuoteIdentifier(identifier string) string
QuoteIdentifier adiciona backticks para identificadores MySQL
func (*MySQLDialect) SetupNodeMap ¶
func (d *MySQLDialect) SetupNodeMap() NodeMap
SetupNodeMap configura o mapa de operadores OData para SQL
func (*MySQLDialect) SetupPrepareMap ¶
func (d *MySQLDialect) SetupPrepareMap() PrepareMap
SetupPrepareMap configura o mapa de preparação de valores
func (*MySQLDialect) SupportsFullTextSearch ¶
func (d *MySQLDialect) SupportsFullTextSearch() bool
SupportsFullTextSearch indica que MySQL suporta full-text search
type MySQLProvider ¶
type MySQLProvider struct {
BaseProvider
}
MySQLProvider implementa o provider para MySQL
func NewMySQLProvider ¶
func NewMySQLProvider(connection ...*sql.DB) *MySQLProvider
NewMySQLProvider cria uma nova instância do provider MySQL
func (*MySQLProvider) BuildDeleteQuery ¶
func (p *MySQLProvider) BuildDeleteQuery(entity EntityMetadata, keyValues map[string]interface{}) (string, []interface{}, error)
BuildDeleteQuery constrói uma query DELETE específica para MySQL
func (*MySQLProvider) BuildInsertQuery ¶
func (p *MySQLProvider) BuildInsertQuery(entity EntityMetadata, data map[string]interface{}) (string, []interface{}, error)
BuildInsertQuery constrói uma query INSERT específica para MySQL
func (*MySQLProvider) BuildSelectQuery ¶
func (p *MySQLProvider) BuildSelectQuery(entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
BuildSelectQuery constrói uma query SELECT específica para MySQL
func (*MySQLProvider) BuildUpdateQuery ¶
func (p *MySQLProvider) BuildUpdateQuery(entity EntityMetadata, data map[string]interface{}, keyValues map[string]interface{}) (string, []interface{}, error)
BuildUpdateQuery constrói uma query UPDATE específica para MySQL
func (*MySQLProvider) Connect ¶
func (p *MySQLProvider) Connect(connectionString string) error
Connect conecta ao banco MySQL
func (*MySQLProvider) FormatDateTime ¶
func (p *MySQLProvider) FormatDateTime(t time.Time) string
FormatDateTime formata uma data/hora para MySQL
func (*MySQLProvider) MapGoTypeToSQL ¶
func (p *MySQLProvider) MapGoTypeToSQL(goType string) string
MapGoTypeToSQL mapeia tipos Go para tipos MySQL específicos
type NamedArgs ¶
type NamedArgs struct {
// contains filtered or unexported fields
}
NamedArgs gerencia argumentos nomeados para queries SQL usando sql.Named
func NewNamedArgs ¶
NewNamedArgs cria uma nova instância de NamedArgs
func (*NamedArgs) AddArg ¶
AddArg adiciona um argumento usando sql.Named e retorna o placeholder apropriado
func (*NamedArgs) GetArgs ¶
func (na *NamedArgs) GetArgs() []interface{}
GetArgs retorna os argumentos como slice de interface{}
func (*NamedArgs) GetNamedArgs ¶
func (na *NamedArgs) GetNamedArgs() []interface{}
GetNamedArgs retorna os argumentos como slice para compatibilidade
type NavigationLink ¶
type NavigationLink struct {
}
NavigationLink representa um link de navegação OData
type NavigationPropertyMetadata ¶
type NavigationPropertyMetadata struct {
}
NavigationPropertyMetadata representa os metadados de uma propriedade de navegação
type NoOpAuditLogger ¶
type NoOpAuditLogger struct{}
NoOpAuditLogger implementa AuditLogger mas não faz nada (quando audit logging está desabilitado)
func (*NoOpAuditLogger) Close ¶
func (l *NoOpAuditLogger) Close() error
Close implementa AuditLogger para NoOpAuditLogger
func (*NoOpAuditLogger) Log ¶
func (l *NoOpAuditLogger) Log(entry AuditLogEntry) error
Log implementa AuditLogger para NoOpAuditLogger (não faz nada)
type ODataError ¶
type ODataError struct {
Code string `json:"code"`
Message string `json:"message"`
Target string `json:"target,omitempty"`
Details []ODataErrorDetail `json:"details,omitempty"`
}
ODataError representa um erro OData
func BadRequestError ¶
func BadRequestError(message string) *ODataError
BadRequestError cria um erro de requisição inválida
func EntityNotFoundError ¶
func EntityNotFoundError(entityName string) *ODataError
EntityNotFoundError cria um erro de entidade não encontrada
func InvalidFilterError ¶
func InvalidFilterError(filter string) *ODataError
InvalidFilterError cria um erro de filtro inválido
func NewODataError ¶
func NewODataError(code, message string) *ODataError
NewODataError cria um novo erro OData
func NewODataErrorWithTarget ¶
func NewODataErrorWithTarget(code, message, target string) *ODataError
NewODataErrorWithTarget cria um novo erro OData com target
func PropertyNotFoundError ¶
func PropertyNotFoundError(propertyName, entityName string) *ODataError
PropertyNotFoundError cria um erro de propriedade não encontrada
type ODataErrorDetail ¶
type ODataErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
Target string `json:"target,omitempty"`
}
ODataErrorDetail representa detalhes adicionais de um erro
type ODataParser ¶
type ODataParser struct {
// contains filtered or unexported fields
}
ODataParser é responsável por fazer o parsing das consultas OData
func GetGlobalParser ¶
func GetGlobalParser() *ODataParser
GetGlobalParser retorna uma instância singleton do parser para melhor performance
func NewODataParser ¶
func NewODataParser() *ODataParser
NewODataParser cria uma nova instância do parser
func (*ODataParser) ParseExpand ¶
func (p *ODataParser) ParseExpand(expand string) ([]ExpandOption, error)
ParseExpand faz o parsing de uma expressão de expansão OData
func (*ODataParser) ParseFilter ¶
func (p *ODataParser) ParseFilter(filter string) ([]FilterExpression, error)
ParseFilter faz o parsing de uma expressão de filtro OData
func (*ODataParser) ParseOrderBy ¶
func (p *ODataParser) ParseOrderBy(orderBy string) ([]OrderByExpression, error)
ParseOrderBy faz o parsing de uma expressão de ordenação OData
func (*ODataParser) ParseQueryOptions ¶
func (p *ODataParser) ParseQueryOptions(values url.Values) (QueryOptions, error)
ParseQueryOptions faz o parsing das opções de consulta OData da URL
func (*ODataParser) ParseQueryOptionsWithConfig ¶
func (p *ODataParser) ParseQueryOptionsWithConfig(values url.Values, config ComplianceConfig) (QueryOptions, error)
ParseQueryOptionsWithConfig faz o parsing com configuração de compliance
func (*ODataParser) ValidateQueryOptions ¶
func (p *ODataParser) ValidateQueryOptions(options QueryOptions) error
ValidateQueryOptions valida as opções de consulta
type ODataResponse ¶
type ODataResponse struct {
Context string `json:"@odata.context,omitempty"`
Count *int64 `json:"@odata.count,omitempty"`
NextLink string `json:"@odata.nextLink,omitempty"`
Value interface{} `json:"value"`
Error *ODataError `json:"error,omitempty"`
}
ODataResponse representa a resposta padrão do OData
type ODataService ¶
type ODataService struct {
Provider DatabaseProvider
Entities map[string]EntityService
}
ODataService é o serviço principal
type ObjectManager ¶
type ObjectManager struct {
// contains filtered or unexported fields
}
ObjectManager implementa funcionalidades ORM similares ao TObjectManager do Aurelius
func CreateFromEventContext ¶
func CreateFromEventContext(ctx *EventContext) *ObjectManager
CreateFromEventContext cria um ObjectManager a partir de um contexto de evento
func CreateObjectManager ¶
func CreateObjectManager(c fiber.Ctx) *ObjectManager
CreateObjectManager cria um novo ObjectManager
func GetObjectManager ¶
func GetObjectManager(c fiber.Ctx) *ObjectManager
GetObjectManager retorna o ObjectManager do fiber context Útil para endpoints customizados (JWT, handlers manuais)
func NewObjectManager ¶
func NewObjectManager(provider DatabaseProvider, ctx context.Context) *ObjectManager
NewObjectManager cria uma nova instância do ObjectManager
func (*ObjectManager) ApplyCachedUpdates ¶
func (om *ObjectManager) ApplyCachedUpdates() error
ApplyCachedUpdates aplica todas as operações pendentes
func (*ObjectManager) BeginTransaction ¶
func (om *ObjectManager) BeginTransaction() (*TxManager, error)
BeginTransaction inicia uma nova transação
func (*ObjectManager) ClearCache ¶
func (om *ObjectManager) ClearCache() error
ClearCache limpa todo o cache
func (*ObjectManager) CommitTransaction ¶
func (om *ObjectManager) CommitTransaction(tx *TxManager) error
CommitTransaction confirma uma transação
func (*ObjectManager) Evict ¶
func (om *ObjectManager) Evict(entity any) error
Evict remove uma entidade do manager
func (*ObjectManager) ExecuteQuery ¶
ExecuteQuery executa uma query customizada
func (*ObjectManager) ExecuteQueryTransaction ¶
func (om *ObjectManager) ExecuteQueryTransaction(tx *TxManager, query string, args ...any) (*sql.Rows, error)
ExecuteQueryTransaction executa query dentro de uma transação
func (*ObjectManager) Find ¶
func (om *ObjectManager) Find(entityName string, key string) (any, error)
Find busca uma entidade por ID
func (*ObjectManager) FindCached ¶
func (om *ObjectManager) FindCached(entityName string, key string) (any, error)
FindCached busca apenas no cache, não toca o banco
func (*ObjectManager) Flush ¶
func (om *ObjectManager) Flush(entity any) error
Flush persiste mudanças de uma entidade específica
func (*ObjectManager) FlushAll ¶
func (om *ObjectManager) FlushAll() error
FlushAll persiste todas as mudanças pendentes
func (*ObjectManager) GetCachedCount ¶
func (om *ObjectManager) GetCachedCount() int
GetCachedCount retorna número de operações pendentes
func (*ObjectManager) GetChangedObjects ¶
func (om *ObjectManager) GetChangedObjects() []any
GetChangedObjects retorna lista de objetos modificados
func (*ObjectManager) GetConnection ¶
func (om *ObjectManager) GetConnection() *sql.DB
GetConnection retorna a conexão do banco
func (*ObjectManager) HasAnyChanges ¶
func (om *ObjectManager) HasAnyChanges() bool
HasAnyChanges verifica se há alguma mudança pendente
func (*ObjectManager) HasChanges ¶
func (om *ObjectManager) HasChanges(entity any) bool
HasChanges verifica se uma entidade foi modificada
func (*ObjectManager) IsAttached ¶
func (om *ObjectManager) IsAttached(entity any) bool
IsAttached verifica se um objeto está attached ao manager
func (*ObjectManager) IsCached ¶
func (om *ObjectManager) IsCached(entityName string, key string) bool
IsCached verifica se uma entidade está no cache
func (*ObjectManager) Merge ¶
func (om *ObjectManager) Merge(entity any) (any, error)
Merge faz merge de um objeto detached com o object manager
func (*ObjectManager) Remove ¶
func (om *ObjectManager) Remove(entity any) error
Remove marca uma entidade para remoção
func (*ObjectManager) RollbackTransaction ¶
func (om *ObjectManager) RollbackTransaction(tx *TxManager) error
RollbackTransaction desfaz uma transação
func (*ObjectManager) Save ¶
func (om *ObjectManager) Save(entity any) error
Save marca uma entidade para inserção
func (*ObjectManager) SaveOrUpdate ¶
func (om *ObjectManager) SaveOrUpdate(entity any) error
SaveOrUpdate salva se novo ou atualiza se existente
func (*ObjectManager) SetBatchSize ¶
func (om *ObjectManager) SetBatchSize(size int)
SetBatchSize configura o tamanho do batch
func (*ObjectManager) SetCachedUpdates ¶
func (om *ObjectManager) SetCachedUpdates(enabled bool)
SetCachedUpdates habilita/desabilita cached updates
func (*ObjectManager) Update ¶
func (om *ObjectManager) Update(entity any) error
Update marca uma entidade para atualização
func (*ObjectManager) WithTransaction ¶
func (om *ObjectManager) WithTransaction(fn func(*TxManager) error) error
WithTransaction executa uma função dentro de uma transação
type OperatorInfo ¶
type OperatorInfo struct {
Precedence int
Associativity Associativity
}
OperatorInfo informações sobre operadores
type OptimizedComplianceConfig ¶
type OptimizedComplianceConfig int
Configuração de compliance OData otimizada
const ( OptimizedComplianceStrict OptimizedComplianceConfig = 0 OptimizedComplianceIgnoreDuplicateKeywords OptimizedComplianceConfig = 1 << iota OptimizedComplianceIgnoreUnknownKeywords OptimizedComplianceIgnoreInvalidComma OptimizedComplianceIgnoreAll OptimizedComplianceConfig = OptimizedComplianceIgnoreDuplicateKeywords | OptimizedComplianceIgnoreUnknownKeywords | OptimizedComplianceIgnoreInvalidComma )
type OracleDialect ¶
type OracleDialect struct{}
OracleDialect implementa SQLDialect para Oracle
func (*OracleDialect) BuildCeilingFunction ¶
func (d *OracleDialect) BuildCeilingFunction(arg string) string
BuildCeilingFunction constrói função CEIL para Oracle
func (*OracleDialect) BuildConcatFunction ¶
func (d *OracleDialect) BuildConcatFunction(args []string) string
BuildConcatFunction constrói concatenação para Oracle
func (*OracleDialect) BuildDateExtractFunction ¶
func (d *OracleDialect) BuildDateExtractFunction(functionName, arg string) string
BuildDateExtractFunction constrói função de extração de data para Oracle
func (*OracleDialect) BuildFullTextPhraseCondition ¶
func (d *OracleDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
BuildFullTextPhraseCondition constrói condição de full-text phrase search para Oracle
func (*OracleDialect) BuildFullTextSearchCondition ¶
func (d *OracleDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
BuildFullTextSearchCondition constrói condição de full-text search para Oracle
func (*OracleDialect) BuildLimitClause ¶
func (d *OracleDialect) BuildLimitClause(top, skip int) string
BuildLimitClause constrói cláusula OFFSET/FETCH para Oracle
func (*OracleDialect) BuildNowFunction ¶
func (d *OracleDialect) BuildNowFunction() string
BuildNowFunction constrói função SYSDATE para Oracle
func (*OracleDialect) BuildSubstringFromFunction ¶
func (d *OracleDialect) BuildSubstringFromFunction(str, start string) string
BuildSubstringFromFunction constrói SUBSTR sem length para Oracle
func (*OracleDialect) BuildSubstringFunction ¶
func (d *OracleDialect) BuildSubstringFunction(str, start, length string) string
BuildSubstringFunction constrói função SUBSTR para Oracle
func (*OracleDialect) FormatDateTime ¶
func (d *OracleDialect) FormatDateTime(t time.Time) string
FormatDateTime formata um time.Time para Oracle
func (*OracleDialect) GetName ¶
func (d *OracleDialect) GetName() string
GetName retorna o nome do dialeto
func (*OracleDialect) QuoteIdentifier ¶
func (d *OracleDialect) QuoteIdentifier(identifier string) string
QuoteIdentifier adiciona aspas duplas para identificadores Oracle
func (*OracleDialect) SetupNodeMap ¶
func (d *OracleDialect) SetupNodeMap() NodeMap
SetupNodeMap configura o mapa de operadores OData para SQL
func (*OracleDialect) SetupPrepareMap ¶
func (d *OracleDialect) SetupPrepareMap() PrepareMap
SetupPrepareMap configura o mapa de preparação de valores
func (*OracleDialect) SupportsFullTextSearch ¶
func (d *OracleDialect) SupportsFullTextSearch() bool
SupportsFullTextSearch indica que Oracle suporta full-text search
type OracleProvider ¶
type OracleProvider struct {
*BaseProvider
}
OracleProvider implementa o DatabaseProvider para Oracle
func NewOracleProvider ¶
func NewOracleProvider(connection ...*sql.DB) *OracleProvider
NewOracleProvider cria um novo OracleProvider
func (*OracleProvider) BuildDeleteQuery ¶
func (p *OracleProvider) BuildDeleteQuery(entity EntityMetadata, keyValues map[string]interface{}) (string, []interface{}, error)
BuildDeleteQuery constrói uma query DELETE específica para Oracle
func (*OracleProvider) BuildInsertQuery ¶
func (p *OracleProvider) BuildInsertQuery(entity EntityMetadata, data map[string]interface{}) (string, []interface{}, error)
BuildInsertQuery constrói uma query INSERT específica para Oracle
func (*OracleProvider) BuildSelectQuery ¶
func (p *OracleProvider) BuildSelectQuery(entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
BuildSelectQuery constrói uma query SELECT específica para Oracle
func (*OracleProvider) BuildSelectQueryOptimized ¶
func (p *OracleProvider) BuildSelectQueryOptimized(ctx context.Context, entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
BuildSelectQueryOptimized constrói query SELECT otimizada para Oracle com proteção contra timeouts
func (*OracleProvider) BuildUpdateQuery ¶
func (p *OracleProvider) BuildUpdateQuery(entity EntityMetadata, data map[string]interface{}, keyValues map[string]interface{}) (string, []interface{}, error)
BuildUpdateQuery constrói uma query UPDATE específica para Oracle
func (*OracleProvider) BuildWhereClause ¶
func (p *OracleProvider) BuildWhereClause(filter string, metadata EntityMetadata) (string, []interface{}, error)
BuildWhereClause sobrescreve o método base para usar placeholders do Oracle
func (*OracleProvider) Connect ¶
func (p *OracleProvider) Connect(connectionString string) error
Connect conecta ao banco Oracle com configurações otimizadas
func (*OracleProvider) ConvertValue ¶
func (p *OracleProvider) ConvertValue(value interface{}, targetType string) (interface{}, error)
ConvertValue implementa conversão de valor para Oracle sem conversão manual
func (*OracleProvider) FormatDateTime ¶
func (p *OracleProvider) FormatDateTime(t time.Time) string
FormatDateTime formata uma data/hora para Oracle
func (*OracleProvider) GetDriverName ¶
func (p *OracleProvider) GetDriverName() string
GetDriverName retorna o nome do driver
func (*OracleProvider) MapGoTypeToSQL ¶
func (p *OracleProvider) MapGoTypeToSQL(goType string) string
MapGoTypeToSQL mapeia tipos Go para tipos Oracle específicos
type OrderByDirection ¶
type OrderByDirection string
OrderByDirection representa a direção da ordenação
const ( OrderAsc OrderByDirection = "asc" OrderDesc OrderByDirection = "desc" )
type OrderByExpression ¶
type OrderByExpression struct {
Property string
Direction OrderByDirection
}
OrderByExpression representa uma expressão de ordenação
type OrderByItem ¶
type OrderByItem struct {
Property string
Direction OrderByDirection
}
OrderByItem representa um item de ordenação (placeholder)
type OrderedEntity ¶
type OrderedEntity struct {
Properties []OrderedProperty `json:"-"`
// contains filtered or unexported fields
}
OrderedEntity representa uma entidade com propriedades ordenadas
func NewOrderedEntity ¶
func NewOrderedEntity() *OrderedEntity
NewOrderedEntity cria uma nova entidade ordenada
func (*OrderedEntity) Get ¶
func (e *OrderedEntity) Get(name string) (interface{}, bool)
Get obtém o valor de uma propriedade
func (*OrderedEntity) MarshalJSON ¶
func (e *OrderedEntity) MarshalJSON() ([]byte, error)
MarshalJSON implementa json.Marshaler mantendo a ordem
func (*OrderedEntity) Set ¶
func (e *OrderedEntity) Set(name string, value interface{})
Set adiciona uma propriedade mantendo a ordem
func (*OrderedEntity) SetNavigationProperty ¶
func (e *OrderedEntity) SetNavigationProperty(name string, navigationURL string)
SetNavigationProperty adiciona uma propriedade de navegação como link
func (*OrderedEntity) ToMap ¶
func (e *OrderedEntity) ToMap() map[string]interface{}
ToMap converte para map (pode perder a ordem)
func (*OrderedEntity) UnmarshalJSON ¶
func (e *OrderedEntity) UnmarshalJSON(data []byte) error
UnmarshalJSON implementa json.Unmarshaler
type OrderedEntityResponse ¶
type OrderedEntityResponse struct {
Context string `json:"@odata.context"`
Fields []ResponseField `json:"-"`
// contains filtered or unexported fields
}
OrderedEntityResponse representa uma resposta de entidade única mantendo a ordem dos campos
func NewOrderedEntityResponse ¶
func NewOrderedEntityResponse(context string, metadata EntityMetadata) *OrderedEntityResponse
NewOrderedEntityResponse cria uma nova resposta de entidade ordenada
func (*OrderedEntityResponse) AddField ¶
func (r *OrderedEntityResponse) AddField(name string, value interface{})
AddField adiciona um campo à resposta
func (*OrderedEntityResponse) AddNavigationLink ¶
func (r *OrderedEntityResponse) AddNavigationLink(name, url string)
AddNavigationLink adiciona um navigation link à resposta
func (*OrderedEntityResponse) MarshalJSON ¶
func (r *OrderedEntityResponse) MarshalJSON() ([]byte, error)
MarshalJSON implementa json.Marshaler mantendo a ordem dos campos conforme os metadados
type OrderedProperty ¶
type OrderedProperty struct {
Name string `json:"name"`
Value interface{} `json:"value"`
}
OrderedProperty representa uma propriedade ordenada
type PaginationInfo ¶
PaginationInfo contém informações de paginação
func GetPaginationInfo ¶
func GetPaginationInfo(top *GoDataTopQuery, skip *GoDataSkipQuery) PaginationInfo
GetPaginationInfo retorna informações de paginação
func (PaginationInfo) GetNextOffset ¶
func (p PaginationInfo) GetNextOffset() int
GetNextOffset calcula o offset para a próxima página
func (PaginationInfo) GetPreviousOffset ¶
func (p PaginationInfo) GetPreviousOffset() int
GetPreviousOffset calcula o offset para a página anterior
func (PaginationInfo) HasPagination ¶
func (p PaginationInfo) HasPagination() bool
HasPagination verifica se há paginação
func (PaginationInfo) IsFirstPage ¶
func (p PaginationInfo) IsFirstPage() bool
IsFirstPage verifica se é a primeira página
type PatchOperation ¶ added in v1.0.13
type PatchOperation struct {
Type string // INSERT, UPDATE, DELETE
Entity map[string]interface{} // Dados da entidade
Keys map[string]interface{} // Chaves identificadoras
EntityName string // Nome da entidade para lookup de serviço
}
PatchOperation representa uma operação a ser executada em um PATCH
type PostgreSQLDialect ¶
type PostgreSQLDialect struct{}
PostgreSQLDialect implementa SQLDialect para PostgreSQL
func (*PostgreSQLDialect) BuildCeilingFunction ¶
func (d *PostgreSQLDialect) BuildCeilingFunction(arg string) string
BuildCeilingFunction constrói função CEILING para PostgreSQL
func (*PostgreSQLDialect) BuildConcatFunction ¶
func (d *PostgreSQLDialect) BuildConcatFunction(args []string) string
BuildConcatFunction constrói função CONCAT para PostgreSQL
func (*PostgreSQLDialect) BuildDateExtractFunction ¶
func (d *PostgreSQLDialect) BuildDateExtractFunction(functionName, arg string) string
BuildDateExtractFunction constrói função de extração de data para PostgreSQL
func (*PostgreSQLDialect) BuildFullTextPhraseCondition ¶
func (d *PostgreSQLDialect) BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
BuildFullTextPhraseCondition constrói condição de full-text phrase search para PostgreSQL
func (*PostgreSQLDialect) BuildFullTextSearchCondition ¶
func (d *PostgreSQLDialect) BuildFullTextSearchCondition(column, term string) (string, interface{})
BuildFullTextSearchCondition constrói condição de full-text search para PostgreSQL
func (*PostgreSQLDialect) BuildLimitClause ¶
func (d *PostgreSQLDialect) BuildLimitClause(top, skip int) string
BuildLimitClause constrói cláusula LIMIT/OFFSET para PostgreSQL
func (*PostgreSQLDialect) BuildNowFunction ¶
func (d *PostgreSQLDialect) BuildNowFunction() string
BuildNowFunction constrói função NOW para PostgreSQL
func (*PostgreSQLDialect) BuildSubstringFromFunction ¶
func (d *PostgreSQLDialect) BuildSubstringFromFunction(str, start string) string
BuildSubstringFromFunction constrói SUBSTRING sem length para PostgreSQL
func (*PostgreSQLDialect) BuildSubstringFunction ¶
func (d *PostgreSQLDialect) BuildSubstringFunction(str, start, length string) string
BuildSubstringFunction constrói função SUBSTRING para PostgreSQL
func (*PostgreSQLDialect) FormatDateTime ¶
func (d *PostgreSQLDialect) FormatDateTime(t time.Time) string
FormatDateTime formata um time.Time para PostgreSQL
func (*PostgreSQLDialect) GetName ¶
func (d *PostgreSQLDialect) GetName() string
GetName retorna o nome do dialeto
func (*PostgreSQLDialect) QuoteIdentifier ¶
func (d *PostgreSQLDialect) QuoteIdentifier(identifier string) string
QuoteIdentifier adiciona aspas duplas para identificadores PostgreSQL
func (*PostgreSQLDialect) SetupNodeMap ¶
func (d *PostgreSQLDialect) SetupNodeMap() NodeMap
SetupNodeMap configura o mapa de operadores OData para SQL
func (*PostgreSQLDialect) SetupPrepareMap ¶
func (d *PostgreSQLDialect) SetupPrepareMap() PrepareMap
SetupPrepareMap configura o mapa de preparação de valores
func (*PostgreSQLDialect) SupportsFullTextSearch ¶
func (d *PostgreSQLDialect) SupportsFullTextSearch() bool
SupportsFullTextSearch indica que PostgreSQL suporta full-text search
type PostgreSQLProvider ¶
type PostgreSQLProvider struct {
BaseProvider
}
PostgreSQLProvider implementa o provider para PostgreSQL
func NewPostgreSQLProvider ¶
func NewPostgreSQLProvider(connection ...*sql.DB) *PostgreSQLProvider
NewPostgreSQLProvider cria uma nova instância do provider PostgreSQL
func (*PostgreSQLProvider) BuildDeleteQuery ¶
func (p *PostgreSQLProvider) BuildDeleteQuery(entity EntityMetadata, keyValues map[string]interface{}) (string, []interface{}, error)
BuildDeleteQuery constrói uma query DELETE específica para PostgreSQL
func (*PostgreSQLProvider) BuildInsertQuery ¶
func (p *PostgreSQLProvider) BuildInsertQuery(entity EntityMetadata, data map[string]interface{}) (string, []interface{}, error)
BuildInsertQuery constrói uma query INSERT específica para PostgreSQL
func (*PostgreSQLProvider) BuildSelectQuery ¶
func (p *PostgreSQLProvider) BuildSelectQuery(entity EntityMetadata, options QueryOptions) (string, []interface{}, error)
BuildSelectQuery constrói uma query SELECT específica para PostgreSQL
func (*PostgreSQLProvider) BuildUpdateQuery ¶
func (p *PostgreSQLProvider) BuildUpdateQuery(entity EntityMetadata, data map[string]interface{}, keyValues map[string]interface{}) (string, []interface{}, error)
BuildUpdateQuery constrói uma query UPDATE específica para PostgreSQL
func (*PostgreSQLProvider) BuildWhereClause ¶ added in v1.0.18
func (p *PostgreSQLProvider) BuildWhereClause(filter string, metadata EntityMetadata) (string, []interface{}, error)
BuildWhereClause constrói a cláusula WHERE específica para PostgreSQL (usa $1, $2, etc.)
func (*PostgreSQLProvider) Connect ¶
func (p *PostgreSQLProvider) Connect(connectionString string) error
Connect conecta ao banco PostgreSQL
func (*PostgreSQLProvider) FormatDateTime ¶
func (p *PostgreSQLProvider) FormatDateTime(t time.Time) string
FormatDateTime formata uma data/hora para PostgreSQL
func (*PostgreSQLProvider) MapGoTypeToSQL ¶
func (p *PostgreSQLProvider) MapGoTypeToSQL(goType string) string
MapGoTypeToSQL mapeia tipos Go para tipos PostgreSQL específicos
type PrepareMap ¶
PrepareMap mapeia funções para preparação de valores
type PropertyMetadata ¶
type PropertyMetadata struct {
Name string
Type string
ColumnName string
IsKey bool
IsNullable bool
MaxLength int
Precision int
Scale int
HasDefault bool
IDGenerator string
SequenceName string
IsCollection bool
RelatedType string
Relationship *RelationshipMetadata
// Novas propriedades para suporte avançado
PropFlags []string // Required, NoInsert, NoUpdate, Lazy, Unique
CascadeFlags []string // SaveUpdate, Remove, Refresh, RemoveOrphan
Schema string // Schema da tabela
Association *AssociationMetadata // Para associações simples
ManyAssociation *ManyAssociationMetadata // Para associações múltiplas
}
PropertyMetadata representa os metadados de uma propriedade
type PropertyTypeMetadata ¶
type PropertyTypeMetadata struct {
Name string `json:"name"`
Type string `json:"type"`
Nullable bool `json:"nullable"`
MaxLength int `json:"maxLength,omitempty"`
Precision int `json:"precision,omitempty"`
Scale int `json:"scale,omitempty"`
IsKey bool `json:"isKey"`
HasDefault bool `json:"hasDefault"`
}
PropertyTypeMetadata representa os metadados de uma propriedade
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder constrói queries SQL a partir de árvores de parse OData
func NewQueryBuilder ¶
func NewQueryBuilder(dialectName string) *QueryBuilder
NewQueryBuilder cria um novo QueryBuilder para o dialeto especificado
func (*QueryBuilder) BuildCompleteQuery ¶
func (qb *QueryBuilder) BuildCompleteQuery(ctx context.Context, metadata EntityMetadata, options QueryOptions) (string, []interface{}, error)
BuildCompleteQuery constrói query SQL completa
func (*QueryBuilder) BuildComputeSQL ¶
func (qb *QueryBuilder) BuildComputeSQL(ctx context.Context, computeOption *ComputeOption, metadata EntityMetadata) (string, []interface{}, error)
BuildComputeSQL constrói SQL para expressões $compute
func (*QueryBuilder) BuildLimitClause ¶
func (qb *QueryBuilder) BuildLimitClause(top, skip int) string
BuildLimitClause constrói cláusula LIMIT/OFFSET
func (*QueryBuilder) BuildOrderByClause ¶
func (qb *QueryBuilder) BuildOrderByClause(metadata EntityMetadata, orderByOptions []OrderByExpression) string
BuildOrderByClause constrói cláusula ORDER BY
func (*QueryBuilder) BuildSearchSQL ¶
func (qb *QueryBuilder) BuildSearchSQL(ctx context.Context, searchOption *SearchOption, metadata EntityMetadata) (string, []interface{}, error)
BuildSearchSQL constrói SQL para expressões $search
func (*QueryBuilder) BuildSearchWhereClause ¶
func (qb *QueryBuilder) BuildSearchWhereClause(ctx context.Context, searchOption *SearchOption, metadata EntityMetadata) (string, []interface{}, error)
BuildSearchWhereClause constrói cláusula WHERE para busca
func (*QueryBuilder) BuildSelectClause ¶
func (qb *QueryBuilder) BuildSelectClause(metadata EntityMetadata, selectOptions []string) string
BuildSelectClause constrói cláusula SELECT
func (*QueryBuilder) BuildWhereClause ¶
func (qb *QueryBuilder) BuildWhereClause(ctx context.Context, tree *ParseNode, metadata EntityMetadata) (string, []interface{}, error)
BuildWhereClause constrói cláusula WHERE a partir de árvore de parse
func (*QueryBuilder) BuildWhereClauseNamed ¶
func (qb *QueryBuilder) BuildWhereClauseNamed(ctx context.Context, tree *ParseNode, metadata EntityMetadata, namedArgs *NamedArgs) (string, error)
BuildWhereClauseNamed constrói cláusula WHERE usando argumentos nomeados
func (*QueryBuilder) CombineSearchWithFilter ¶
func (qb *QueryBuilder) CombineSearchWithFilter(ctx context.Context, searchSQL, filterSQL string, searchParams, filterParams []interface{}) (string, []interface{}, error)
CombineSearchWithFilter combina busca com filtro existente
func (*QueryBuilder) QuoteIdentifier ¶
func (qb *QueryBuilder) QuoteIdentifier(identifier string) string
QuoteIdentifier adiciona aspas aos identificadores quando necessário
type QueryOptions ¶
type QueryOptions struct {
Filter *GoDataFilterQuery
OrderBy string
Select *GoDataSelectQuery
Expand *GoDataExpandQuery
Skip *GoDataSkipQuery
Top *GoDataTopQuery
Count *GoDataCountQuery
Compute *ComputeOption
Search *SearchOption
}
QueryOptions representa as opções de consulta OData
type QueryParseError ¶
QueryParseError representa um erro de parsing de query
func (*QueryParseError) Error ¶
func (e *QueryParseError) Error() string
type RateLimitConfig ¶
type RateLimitConfig struct {
Enabled bool // Se o rate limit está habilitado
RequestsPerMinute int // Número de requisições por minuto
BurstSize int // Tamanho do burst (requisições simultâneas)
WindowSize time.Duration // Tamanho da janela de tempo
KeyGenerator func(c fiber.Ctx) string // Função para gerar chave única
SkipSuccessful bool // Pular requisições bem-sucedidas
SkipFailed bool // Pular requisições com falha
Headers bool // Incluir headers de rate limit na resposta
}
RateLimitConfig representa as configurações do rate limit
func DefaultRateLimitConfig ¶
func DefaultRateLimitConfig() *RateLimitConfig
DefaultRateLimitConfig retorna uma configuração padrão de rate limit NOTA: Rate limiting está HABILITADO por padrão para proteção contra abuso. Para desabilitar, defina Enabled = false na configuração.
type RateLimitInfo ¶
type RateLimitInfo struct {
Allowed bool // Se a requisição é permitida
Limit int // Limite total de requisições
Remaining int // Requisições restantes
ResetTime time.Time // Quando o limite será resetado
RetryAfter int // Segundos para tentar novamente (se bloqueado)
}
RateLimitInfo contém informações sobre o status do rate limit
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implementa o controle de rate limit
func NewRateLimiter ¶
func NewRateLimiter(config *RateLimitConfig) *RateLimiter
NewRateLimiter cria uma nova instância do rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string) (bool, RateLimitInfo)
Allow verifica se uma requisição é permitida
type RelationshipMetadata ¶
type RelationshipMetadata struct {
LocalProperty string
ReferencedProperty string
OnDelete string
OnUpdate string
}
RelationshipMetadata representa os metadados de um relacionamento
type ResponseField ¶
type ResponseField struct {
Name string `json:"-"`
Value interface{} `json:"-"`
}
ResponseField representa um campo na resposta
type ResponseNavigationLink ¶
type ResponseNavigationLink struct {
}
ResponseNavigationLink representa um navigation link na resposta
type SQLDialect ¶
type SQLDialect interface {
// GetName retorna o nome do dialeto (mysql, postgresql, oracle)
GetName() string
// SetupNodeMap configura o mapa de operadores OData para SQL
SetupNodeMap() NodeMap
// SetupPrepareMap configura o mapa de preparação de valores
SetupPrepareMap() PrepareMap
// BuildLimitClause constrói cláusula LIMIT/OFFSET (ou equivalente)
BuildLimitClause(top, skip int) string
// QuoteIdentifier adiciona quotes apropriados para identificadores
QuoteIdentifier(identifier string) string
// FormatDateTime formata um time.Time para o formato do banco
FormatDateTime(t time.Time) string
// BuildCeilingFunction constrói função CEILING/CEIL
BuildCeilingFunction(arg string) string
// BuildConcatFunction constrói função de concatenação
BuildConcatFunction(args []string) string
// BuildSubstringFunction constrói função SUBSTRING/SUBSTR
BuildSubstringFunction(str, start, length string) string
// BuildSubstringFromFunction constrói SUBSTRING sem length
BuildSubstringFromFunction(str, start string) string
// BuildDateExtractFunction constrói função de extração de data (YEAR, MONTH, etc)
BuildDateExtractFunction(functionName, arg string) string
// BuildNowFunction constrói função NOW/SYSDATE
BuildNowFunction() string
// SupportsFullTextSearch indica se o banco suporta full-text search
SupportsFullTextSearch() bool
// BuildFullTextSearchCondition constrói condição de full-text search
BuildFullTextSearchCondition(column, term string) (string, interface{})
// BuildFullTextPhraseCondition constrói condição de full-text phrase search
BuildFullTextPhraseCondition(column, phrase string) (string, interface{})
}
SQLDialect define a interface para dialetos SQL específicos de cada provider
func GetDialect ¶
func GetDialect(name string) SQLDialect
GetDialect retorna a implementação de dialect apropriada
type SchemaMetadata ¶
type SchemaMetadata struct {
Namespace string `json:"namespace"`
Alias string `json:"alias,omitempty"`
EntityTypes []EntityTypeMetadata `json:"entityTypes"`
EntitySets []EntitySetMetadata `json:"entitySets"`
EntityContainer EntityContainerMetadata `json:"entityContainer"`
}
SchemaMetadata representa os metadados de um schema
type SearchExpression ¶
type SearchExpression struct {
Type SearchExpressionType
Value string
Children []*SearchExpression
}
SearchExpression representa uma expressão de busca
type SearchExpressionType ¶
type SearchExpressionType int
SearchExpressionType tipos de expressões de busca
const ( SearchExpressionTerm SearchExpressionType = iota SearchExpressionPhrase SearchExpressionAND SearchExpressionOR SearchExpressionNOT SearchExpressionGroup )
type SearchOption ¶
type SearchOption struct {
Expression *SearchExpression
RawQuery string
}
SearchOption representa uma opção de busca
type SearchParser ¶
type SearchParser struct {
// contains filtered or unexported fields
}
SearchParser parser para expressões $search
func NewSearchParser ¶
func NewSearchParser() *SearchParser
NewSearchParser cria um novo parser de search
func (*SearchParser) ExtractSearchTerms ¶
func (p *SearchParser) ExtractSearchTerms(expr *SearchExpression) []string
ExtractSearchTerms extrai todos os termos de busca de uma expressão
func (*SearchParser) GetSearchComplexity ¶
func (p *SearchParser) GetSearchComplexity(expr *SearchExpression) int
GetSearchComplexity calcula a complexidade de uma expressão de busca
func (*SearchParser) GetSearchableProperties ¶
func (p *SearchParser) GetSearchableProperties(metadata EntityMetadata) []PropertyMetadata
GetSearchableProperties retorna propriedades que podem ser pesquisadas
func (*SearchParser) OptimizeSearchExpression ¶
func (p *SearchParser) OptimizeSearchExpression(expr *SearchExpression) *SearchExpression
OptimizeSearchExpression otimiza uma expressão de busca
func (*SearchParser) ParseSearch ¶
func (p *SearchParser) ParseSearch(ctx context.Context, searchStr string) (*SearchOption, error)
ParseSearch analisa uma string $search
func (*SearchParser) ValidateSearchExpression ¶
func (p *SearchParser) ValidateSearchExpression(expr *SearchExpression) error
ValidateSearchExpression valida uma expressão de busca
type SearchTokenType ¶
type SearchTokenType int
SearchTokenType representa tipos de tokens para $search
const ( SearchTokenTerm SearchTokenType = iota SearchTokenPhrase SearchTokenAND SearchTokenOR SearchTokenNOT SearchTokenOpenParen SearchTokenCloseParen SearchTokenWhitespace )
func (SearchTokenType) Value ¶
func (s SearchTokenType) Value() int
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
// Habilita/desabilita todos os headers de segurança
Enabled bool
// Headers individuais (podem ser habilitados/desabilitados individualmente)
XFrameOptions string // DENY, SAMEORIGIN, ALLOW-FROM uri
XContentTypeOptions string // nosniff
XXSSProtection string // 1; mode=block
ContentSecurityPolicy string // default-src 'self'; ...
StrictTransportSecurity string // max-age=31536000; includeSubDomains
ReferrerPolicy string // strict-origin-when-cross-origin, no-referrer, etc
PermissionsPolicy string // camera=(), microphone=(), geolocation=(), etc
// Headers customizados adicionais
CustomHeaders map[string]string
}
SecurityHeadersConfig configurações de security headers
func DefaultSecurityHeadersConfig ¶
func DefaultSecurityHeadersConfig() *SecurityHeadersConfig
DefaultSecurityHeadersConfig retorna configuração padrão de security headers
func DisableSecurityHeaders ¶
func DisableSecurityHeaders() *SecurityHeadersConfig
DisableSecurityHeaders desabilita headers de segurança
func RelaxedSecurityHeadersConfig ¶
func RelaxedSecurityHeadersConfig() *SecurityHeadersConfig
RelaxedSecurityHeadersConfig retorna configuração mais permissiva (para desenvolvimento)
func StrictSecurityHeadersConfig ¶
func StrictSecurityHeadersConfig() *SecurityHeadersConfig
StrictSecurityHeadersConfig retorna configuração mais restritiva
type SelectItem ¶
type SelectItem struct {
Segments []*Token
}
SelectItem representa um item individual de seleção
type SemanticType ¶
type SemanticType int
SemanticType representa o tipo semântico de um token
const ( SemanticTypeUnknown SemanticType = iota SemanticTypeProperty SemanticTypeFunction SemanticTypeOperator SemanticTypeValue SemanticTypeKeyword )
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server representa o servidor OData
func NewServer ¶
func NewServer() *Server
NewServer cria uma nova instância do servidor OData Carrega automaticamente configurações multi-tenant do .env Se não conseguir, retorna um servidor básico para configuração manual
func NewServerWithEnv ¶
func NewServerWithEnv(provider DatabaseProvider) *Server
NewServerWithEnv cria uma nova instância do servidor OData carregando configurações do .env
func NewServerWithProvider ¶
func NewServerWithProvider(provider DatabaseProvider, host string, port int, routePrefix string) *Server
NewServerWithProvider cria servidor com provider específico (mantido para compatibilidade) Carrega automaticamente configurações multi-tenant do .env
func (*Server) ApplyConfig ¶
func (s *Server) ApplyConfig(config *ServerConfig) *Server
ApplyConfig aplica uma configuração completa ao servidor
func (*Server) AutoRegisterEntities ¶
AutoRegisterEntities registra múltiplas entidades automaticamente
func (*Server) CheckEntityReadOnly ¶
CheckEntityReadOnly verifica se a entidade é apenas leitura
func (*Server) DatabaseMiddleware ¶
DatabaseMiddleware middleware que adiciona conexão de banco no contexto
func (*Server) Delete ¶
Delete registra rota DELETE com prefixo automático O path fornecido será prefixado automaticamente com RoutePrefix Exemplo: server.Delete("/auth/revoke", handler) -> /api/v1/auth/revoke
func (*Server) DisableRateLimit ¶
DisableRateLimit desabilita rate limiting
func (*Server) GenerateJWT ¶
GenerateJWT gera um token JWT (wrapper do método do servidor para compatibilidade)
func (*Server) GenerateRefreshToken ¶
GenerateRefreshToken gera um refresh token (wrapper do método do servidor para compatibilidade)
func (*Server) Get ¶
Get registra rota GET com prefixo automático O path fornecido será prefixado automaticamente com RoutePrefix Exemplo: server.Post("/auth/login", handler) -> /api/v1/auth/login
func (*Server) GetAddress ¶
GetAddress retorna o endereço do servidor
func (*Server) GetConfig ¶
func (s *Server) GetConfig() *ServerConfig
GetConfig retorna a configuração do servidor
func (*Server) GetEntities ¶
func (s *Server) GetEntities() map[string]EntityService
GetEntities retorna a lista de entidades registradas
func (*Server) GetEntityAuth ¶
func (s *Server) GetEntityAuth(name string) (EntityAuthConfig, bool)
GetEntityAuth retorna a configuração de autenticação de uma entidade
func (*Server) GetEntityService ¶
func (s *Server) GetEntityService(name string) EntityService
GetEntityService retorna o EntityService registrado para o nome especificado
func (*Server) GetEventManager ¶
func (s *Server) GetEventManager() *EntityEventManager
GetEventManager retorna o gerenciador de eventos
func (*Server) GetHandler ¶
GetHandler retorna o handler HTTP do servidor (para compatibilidade)
func (*Server) GetRateLimitConfig ¶
func (s *Server) GetRateLimitConfig() *RateLimitConfig
GetRateLimitConfig retorna a configuração atual do rate limit
func (*Server) HandleBatch ¶
HandleBatch é o handler para requisições $batch
func (*Server) IsRunningAsService ¶
IsRunningAsService verifica se o processo está rodando como serviço do sistema
func (*Server) MultiTenantHealthCheck ¶
MultiTenantHealthCheck middleware para verificar saúde do tenant
func (*Server) NewRouterBasicAuth ¶
func (s *Server) NewRouterBasicAuth(validator func(string, string) bool, config ...*BasicAuthConfig) fiber.Handler
NewRouterBasicAuth retorna middleware Basic Auth do Fiber v3 Aceita um validator customizado ou usa config com map de usuários
func (*Server) NewRouterJWTAuth ¶
NewRouterJWTAuth retorna middleware JWT Carrega config do .env se não fornecido
func (*Server) OnEntityDeleted ¶
OnEntityDeleted registra um handler para o evento EntityDeleted
func (*Server) OnEntityDeletedGlobal ¶
OnEntityDeletedGlobal registra um handler global para o evento EntityDeleted
func (*Server) OnEntityDeleting ¶
OnEntityDeleting registra um handler para o evento EntityDeleting
func (*Server) OnEntityDeletingGlobal ¶
OnEntityDeletingGlobal registra um handler global para o evento EntityDeleting
func (*Server) OnEntityError ¶
OnEntityError registra um handler para o evento EntityError
func (*Server) OnEntityErrorGlobal ¶
OnEntityErrorGlobal registra um handler global para o evento EntityError
func (*Server) OnEntityGet ¶
OnEntityGet registra um handler para o evento EntityGet
func (*Server) OnEntityGetGlobal ¶
OnEntityGetGlobal registra um handler global para o evento EntityGet
func (*Server) OnEntityInserted ¶
OnEntityInserted registra um handler para o evento EntityInserted
func (*Server) OnEntityInsertedGlobal ¶
OnEntityInsertedGlobal registra um handler global para o evento EntityInserted
func (*Server) OnEntityInserting ¶
OnEntityInserting registra um handler para o evento EntityInserting
func (*Server) OnEntityInsertingGlobal ¶
OnEntityInsertingGlobal registra um handler global para o evento EntityInserting
func (*Server) OnEntityList ¶
OnEntityList registra um handler para o evento EntityList
func (*Server) OnEntityListGlobal ¶
OnEntityListGlobal registra um handler global para o evento EntityList
func (*Server) OnEntityModified ¶
OnEntityModified registra um handler para o evento EntityModified
func (*Server) OnEntityModifiedGlobal ¶
OnEntityModifiedGlobal registra um handler global para o evento EntityModified
func (*Server) OnEntityModifying ¶
OnEntityModifying registra um handler para o evento EntityModifying
func (*Server) OnEntityModifyingGlobal ¶
OnEntityModifyingGlobal registra um handler global para o evento EntityModifying
func (*Server) Patch ¶
Patch registra rota PATCH com prefixo automático O path fornecido será prefixado automaticamente com RoutePrefix Exemplo: server.Patch("/auth/refresh", handler) -> /api/v1/auth/refresh
func (*Server) PayloadLoggerMiddleware ¶
PayloadLoggerMiddleware retorna um middleware que loga request e response payloads quando habilitado
func (*Server) Post ¶
Post registra rota POST com prefixo automático O path fornecido será prefixado automaticamente com RoutePrefix Exemplo: server.Post("/auth/login", handler) -> /api/v1/auth/login
func (*Server) Put ¶
Put registra rota PUT com prefixo automático O path fornecido será prefixado automaticamente com RoutePrefix Exemplo: server.Put("/auth/update", handler) -> /api/v1/auth/update
func (*Server) RateLimitMiddleware ¶
RateLimitMiddleware cria um middleware de rate limit
func (*Server) RegisterEntity ¶
func (s *Server) RegisterEntity(name string, entity interface{}, opts ...EntityOption) error
RegisterEntity registra uma entidade no servidor usando mapeamento automático Aceita EntityOptions para configuração adicional (como WithAuth, WithReadOnly)
func (*Server) RegisterEntityWithService ¶
func (s *Server) RegisterEntityWithService(name string, service EntityService) error
RegisterEntityWithService registra uma entidade com um serviço customizado
func (*Server) RequireEntityAuth ¶
RequireEntityAuth aplica middleware de autenticação baseado na configuração da entidade
func (*Server) RequireTenant ¶
RequireTenant middleware que requer um tenant específico
func (*Server) SetAllowedHeaders ¶
SetAllowedHeaders permite configurar headers permitidos para CORS
func (*Server) SetAllowedMethods ¶
SetAllowedMethods permite configurar métodos HTTP permitidos para CORS
func (*Server) SetAllowedOrigins ¶
SetAllowedOrigins permite configurar origens permitidas para CORS
func (*Server) SetAuditLog ¶
SetAuditLog permite configurar audit logging
func (*Server) SetEnableLogging ¶
SetEnableLogging permite habilitar/desabilitar logging
func (*Server) SetLogLevel ¶
SetLogLevel permite configurar o nível de log
func (*Server) SetMaxRequestSize ¶
SetMaxRequestSize permite configurar o tamanho máximo de requisição
func (*Server) SetProvider ¶
func (s *Server) SetProvider(provider DatabaseProvider) *Server
SetProvider permite trocar o provider de banco de dados
func (*Server) SetRateLimit ¶
SetRateLimit permite configurar rate limiting
func (*Server) SetRateLimitConfig ¶
func (s *Server) SetRateLimitConfig(config *RateLimitConfig)
SetRateLimitConfig configura o rate limiter do servidor
func (*Server) SetRoutePrefix ¶
SetRoutePrefix permite sobrescrever o prefixo das rotas
func (*Server) SetSecurityHeaders ¶
SetSecurityHeaders permite habilitar/desabilitar security headers
func (*Server) SetShutdownTimeout ¶
SetShutdownTimeout permite configurar o timeout de shutdown
func (*Server) Start ¶
Start inicia o servidor HTTP Detecta automaticamente se deve executar como serviço ou normalmente
func (*Server) Stop ¶
Stop para o servidor gracefully Unifica StopService e Shutdown em um único método
func (*Server) TenantInfo ¶
TenantInfo middleware que adiciona informações do tenant no contexto
func (*Server) TenantMiddleware ¶
TenantMiddleware middleware para identificação de tenant
func (*Server) TenantRateLimitMiddleware ¶
TenantRateLimitMiddleware middleware para limitar requests por tenant
func (*Server) TenantStatsMiddleware ¶
TenantStatsMiddleware middleware para coletar estatísticas por tenant
func (*Server) TenantSwitchMiddleware ¶
TenantSwitchMiddleware middleware para permitir mudança de tenant em tempo de execução
type ServerConfig ¶
type ServerConfig struct {
// Configurações básicas
Name string
DisplayName string
Description string
// Configurações de host e porta
Host string
Port int
// Configurações de TLS
TLSConfig *tls.Config
CertFile string
CertKeyFile string
// Configurações de CORS
EnableCORS bool
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
ExposedHeaders []string
AllowCredentials bool
// Configurações de log
EnableLogging bool
LogLevel string
LogFile string
// Configurações de middleware
EnableCompression bool
MaxRequestSize int64
// Configurações de graceful shutdown
ShutdownTimeout time.Duration
// Configurações de banco de dados
DBLogSQL bool // Habilita/desabilita logs de queries SQL
// Configurações de prefixo
RoutePrefix string
// Configurações JWT
EnableJWT bool
JWTConfig *JWTConfig
RequireAuth bool // Se true, todas as rotas requerem autenticação por padrão
// Configurações de Rate Limit
RateLimitConfig *RateLimitConfig
// Configurações de Validação
ValidationConfig *ValidationConfig
// Configurações de Security Headers
SecurityHeadersConfig *SecurityHeadersConfig
// Configurações de Audit Logging
AuditLogConfig *AuditLogConfig
// Performance: Desabilita JOIN automático para expand (força batching)
// Default: false (usa detecção automática baseada em relacionamento)
DisableJoinForExpand bool
// Configurações de PATCH OData 4.01
PatchRemovedFormat string // Formato aceito para @odata.removed: "both", "empty", "with_reason" (default: "both")
}
ServerConfig representa as configurações do servidor
func DefaultServerConfig ¶
func DefaultServerConfig() *ServerConfig
DefaultServerConfig retorna uma configuração padrão do servidor
type ServiceWrapper ¶
type ServiceWrapper struct {
// contains filtered or unexported fields
}
ServiceWrapper implementa a interface service.Interface para o servidor GoData
type StderrAuditLogger ¶
type StderrAuditLogger struct {
// contains filtered or unexported fields
}
StderrAuditLogger implementa AuditLogger escrevendo em stderr
func (*StderrAuditLogger) Close ¶
func (l *StderrAuditLogger) Close() error
Close implementa AuditLogger para StderrAuditLogger
func (*StderrAuditLogger) Log ¶
func (l *StderrAuditLogger) Log(entry AuditLogEntry) error
Log implementa AuditLogger para StderrAuditLogger
type StdoutAuditLogger ¶
type StdoutAuditLogger struct {
// contains filtered or unexported fields
}
StdoutAuditLogger implementa AuditLogger escrevendo em stdout
func (*StdoutAuditLogger) Close ¶
func (l *StdoutAuditLogger) Close() error
Close implementa AuditLogger para StdoutAuditLogger
func (*StdoutAuditLogger) Log ¶
func (l *StdoutAuditLogger) Log(entry AuditLogEntry) error
Log implementa AuditLogger para StdoutAuditLogger
type String ¶
String representa uma string que pode ser null
func (String) MarshalJSON ¶
MarshalJSON implementa json.Marshaler
func (*String) UnmarshalJSON ¶
UnmarshalJSON implementa json.Unmarshaler
type TenantConfig ¶
type TenantConfig struct {
TenantID string
DBDriver string
DBHost string
DBPort string
DBName string
DBUser string
DBPassword string
DBSchema string
DBConnectionString string
DBMaxOpenConns int
DBMaxIdleConns int
DBConnMaxLifetime time.Duration
// Configurações específicas do tenant
CustomSettings map[string]string
}
TenantConfig representa configurações específicas de um tenant
func GetCurrentTenantConfig ¶
func GetCurrentTenantConfig(c fiber.Ctx) *TenantConfig
GetCurrentTenantConfig retorna a configuração do tenant atual
func (*TenantConfig) BuildConnectionString ¶
func (tc *TenantConfig) BuildConnectionString() string
BuildConnectionString constrói a string de conexão para um tenant
type TenantContextKeyType ¶
type TenantContextKeyType struct{}
TenantContext chave para armazenar tenant no contexto TenantContextKeyType define um tipo customizado para chaves de contexto
type Time ¶
Time representa um time.Time que pode ser null
func (Time) MarshalJSON ¶
MarshalJSON implementa json.Marshaler
func (*Time) UnmarshalJSON ¶
UnmarshalJSON implementa json.Unmarshaler
type Token ¶
type Token struct {
Type int
Value string
SemanticType SemanticType
SemanticReference interface{}
}
Token representa um token no parsing
type TokenQueue ¶
type TokenQueue struct {
// contains filtered or unexported fields
}
TokenQueue representa uma fila de tokens
func (*TokenQueue) Dequeue ¶
func (q *TokenQueue) Dequeue() *Token
Dequeue remove e retorna o token do início da fila
func (*TokenQueue) Enqueue ¶
func (q *TokenQueue) Enqueue(token *Token)
Enqueue adiciona um token ao final da fila
func (*TokenQueue) GetValue ¶
func (q *TokenQueue) GetValue() string
GetValue retorna o valor concatenado de todos os tokens restantes na fila
func (*TokenQueue) GetValueUntilSeparator ¶
func (q *TokenQueue) GetValueUntilSeparator() string
GetValueUntilSeparator retorna o valor concatenado dos tokens até encontrar um separador (; ou ,)
func (*TokenQueue) Peek ¶
func (q *TokenQueue) Peek() *Token
Peek retorna o token do início da fila sem removê-lo
func (*TokenQueue) ToSlice ¶
func (q *TokenQueue) ToSlice() []*Token
ToSlice retorna todos os tokens restantes como slice
type TokenStack ¶
type TokenStack struct {
// contains filtered or unexported fields
}
TokenStack representa uma pilha de tokens
func (*TokenStack) Peek ¶
func (s *TokenStack) Peek() *Token
Peek retorna o token do topo da pilha sem removê-lo
func (*TokenStack) Pop ¶
func (s *TokenStack) Pop() *Token
Pop remove e retorna o token do topo da pilha
func (*TokenStack) Push ¶
func (s *TokenStack) Push(token *Token)
Push adiciona um token ao topo da pilha
type Tokenizer ¶
type Tokenizer struct {
// contains filtered or unexported fields
}
Tokenizer é responsável por tokenizar strings
var GlobalFilterTokenizer *Tokenizer
GlobalFilterTokenizer é o tokenizer singleton para filtros
func CreateComputeTokenizer ¶
func CreateComputeTokenizer() *Tokenizer
CreateComputeTokenizer cria um tokenizer específico para $compute
func CreateSearchTokenizer ¶
func CreateSearchTokenizer() *Tokenizer
CreateSearchTokenizer cria um tokenizer específico para $search
func GetGlobalFilterTokenizer ¶
func GetGlobalFilterTokenizer() *Tokenizer
GetGlobalFilterTokenizer retorna o tokenizer global para filtros
func NewExpandTokenizer ¶
func NewExpandTokenizer() *Tokenizer
NewExpandTokenizer cria um novo tokenizer para $expand
type TxManager ¶
type TxManager struct {
// contains filtered or unexported fields
}
TxManager representa uma transação ativa
type URLParser ¶
type URLParser struct {
// contains filtered or unexported fields
}
URLParser é um parser de URL otimizado que combina performance e robustez
func NewOptimizedURLParser ¶
NewOptimizedURLParser cria um novo parser otimizado (mantido para compatibilidade)
func (*URLParser) CleanODataValue ¶
CleanODataValue limpa um valor OData removendo caracteres desnecessários
func (*URLParser) ClearCache ¶
func (up *URLParser) ClearCache()
ClearCache limpa o cache para liberar memória
func (*URLParser) ExtractODataSystemParams ¶
ExtractODataSystemParams extrai parâmetros do sistema OData ($filter, $orderby, etc.)
func (*URLParser) GetCacheStats ¶
GetCacheStats retorna estatísticas do cache
func (*URLParser) NormalizeODataQuery ¶
NormalizeODataQuery é um alias para NormalizeODataQueryFast para compatibilidade
func (*URLParser) NormalizeODataQueryFast ¶
NormalizeODataQueryFast normalização otimizada
func (*URLParser) ParseExpandValue ¶
ParseExpandValue faz parsing específico de valores $expand
func (*URLParser) ParseFilterValue ¶
ParseFilterValue faz parsing específico de valores $filter
func (*URLParser) ParseODataURL ¶
ParseODataURL faz o parsing completo de uma URL OData
func (*URLParser) ParseQuery ¶
ParseQuery é um alias para ParseQueryFast para compatibilidade
func (*URLParser) ParseQueryFast ¶
ParseQueryFast faz parsing rápido usando url.Values padrão quando possível
func (*URLParser) ValidateODataQuery ¶
ValidateODataQuery é um alias para ValidateODataQueryFast para compatibilidade
func (*URLParser) ValidateODataQueryFast ¶
ValidateODataQueryFast validação otimizada
type UserIdentity ¶
type UserIdentity struct {
Username string `json:"username"`
Roles []string `json:"roles"`
Scopes []string `json:"scopes"`
Admin bool `json:"admin"`
Custom map[string]interface{} `json:"custom"`
}
UserIdentity representa a identidade do usuário autenticado
func GetCurrentUser ¶
func GetCurrentUser(c fiber.Ctx) *UserIdentity
GetCurrentUser obtém o usuário atual do contexto
func (*UserIdentity) GetCustomClaim ¶
func (u *UserIdentity) GetCustomClaim(key string) (interface{}, bool)
GetCustomClaim retorna um valor custom do usuário
func (*UserIdentity) HasAnyRole ¶
func (u *UserIdentity) HasAnyRole(roles ...string) bool
HasAnyRole verifica se o usuário possui pelo menos uma das roles
func (*UserIdentity) HasAnyScope ¶
func (u *UserIdentity) HasAnyScope(scopes ...string) bool
HasAnyScope verifica se o usuário possui pelo menos um dos scopes
func (*UserIdentity) HasRole ¶
func (u *UserIdentity) HasRole(role string) bool
HasRole verifica se o usuário possui uma role específica
func (*UserIdentity) HasScope ¶
func (u *UserIdentity) HasScope(scope string) bool
HasScope verifica se o usuário possui um scope específico
type ValidationConfig ¶
type ValidationConfig struct {
// Limites de tamanho
MaxFilterLength int // Tamanho máximo de string $filter
MaxSearchLength int // Tamanho máximo de string $search
MaxSelectLength int // Tamanho máximo de string $select
MaxOrderByLength int // Tamanho máximo de string $orderby
MaxExpandDepth int // Profundidade máxima de $expand
MaxTopValue int // Valor máximo de $top
// Validações de caracteres
AllowedPropertyChars string // Regex de caracteres permitidos em nomes de propriedades
// XSS Protection
EnableXSSProtection bool // Habilita sanitização de XSS
// Validações customizadas
CustomPropertyValidator func(name string) error
}
ValidationConfig configurações de validação de inputs
func DefaultValidationConfig ¶
func DefaultValidationConfig() *ValidationConfig
DefaultValidationConfig retorna configuração padrão de validação
Source Files
¶
- audit_log.go
- auth_bridge.go
- basic.go
- batch.go
- compute_parser.go
- config.go
- constants.go
- context_helpers.go
- count_parser.go
- dialect.go
- dialect_default.go
- dialect_mysql.go
- dialect_oracle.go
- dialect_postgresql.go
- entity_mapper.go
- entity_service.go
- events.go
- expand_batching.go
- expand_handler.go
- expand_parser.go
- expression_parser.go
- filter_parser.go
- handlers.go
- helpers.go
- jwt.go
- mapping.go
- multi_tenant_config.go
- multi_tenant_entity_service.go
- multi_tenant_middleware.go
- multi_tenant_pool.go
- nullable_types.go
- object_manager.go
- parser.go
- patch_processor.go
- payload_logger_middleware.go
- provider_base.go
- provider_mysql.go
- provider_oracle.go
- provider_postgresql.go
- query_builder.go
- query_executor.go
- rate_limit.go
- result_processor.go
- routing.go
- search_parser.go
- security_middleware.go
- select_parser.go
- server.go
- server_config.go
- server_config_setters.go
- server_events.go
- server_getters.go
- server_middleware.go
- server_wrappers.go
- service.go
- tokenizer.go
- topskip_parser.go
- types.go
- url_parser.go
- validation.go