odata

package
v1.0.21 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
const (
	DefaultRateLimitPerMinute = 100         // 100 requests per minute
	DefaultRateLimitBurstSize = 10          // Allow 10 concurrent requests
	DefaultRateLimitWindow    = time.Minute // 1 minute window
)

Rate Limiting

View Source
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

View Source
const (
	DefaultPageSize = 50               // Default page size if $top not specified
	DefaultTimeout  = 30 * time.Second // Default query timeout
)

Query Defaults

View Source
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

View Source
const (
	DefaultHealthCheckPeriod = 30 * time.Second // Health check interval
	MaxFailureCount          = 3                // Mark unhealthy after 3 failures
)

Health Check

View Source
const (
	MaxPropertyNameLength = 100                 // Max property name length
	PropertyNamePattern   = `^[a-zA-Z0-9_\.]+$` // Allowed chars in property names
)

Property Name Validation

View Source
const (
	DefaultTopLimit  = DefaultMaxTopValue  // Usa constante centralizada
	DefaultSkipLimit = DefaultMaxSkipValue // Usa constante centralizada
	MinTopValue      = 0
	MinSkipValue     = 0
)

Constantes para limites padrão

View Source
const (
	MaxLogEntrySize = 10000 // Max size of single log entry
)

Logging

View Source
const (
	UserContextKey = "user" // Chave para armazenar usuário no contexto
)

Constantes para chaves do contexto

Variables

View Source
var FiberContextKey = FiberContextKeyType{}
View Source
var GlobalExpandTokenizer = NewExpandTokenizer()

GlobalExpandTokenizer é o tokenizer global singleton para $expand

View Source
var TenantContextKey = TenantContextKeyType{}

Functions

func APIKeyBasedKeyGenerator

func APIKeyBasedKeyGenerator(c fiber.Ctx) string

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

func CustomKeyGenerator(fn func(c fiber.Ctx) string) func(c fiber.Ctx) string

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

func GenerateJWT(claims jwt.MapClaims, config ...*JWTConfig) (string, error)

GenerateJWT gera um token JWT (função standalone)

func GenerateRefreshToken

func GenerateRefreshToken(claims jwt.MapClaims, config ...*JWTConfig) (string, error)

GenerateRefreshToken gera um refresh token (função standalone)

func GetBasicAuthUsername

func GetBasicAuthUsername(c fiber.Ctx) string

GetBasicAuthUsername retorna o username do Basic Auth do contexto

func GetConnection

func GetConnection(c fiber.Ctx) *sql.DB

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

func GetCurrentTenant(c fiber.Ctx) string

GetCurrentTenant retorna o tenant atual do contexto

func GetDBFromContext

func GetDBFromContext(c fiber.Ctx) *sql.DB

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

func GetJWTClaims(c fiber.Ctx) jwt.MapClaims

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 GetTopValue

func GetTopValue(top *GoDataTopQuery) int

GetTopValue retorna o valor de $top

func HasRole

func HasRole(c fiber.Ctx, role string) bool

HasRole verifica se o usuário atual possui uma role específica

func HasScope

func HasScope(c fiber.Ctx, scope string) bool

HasScope verifica se o usuário atual possui um scope específico

func IsAdmin

func IsAdmin(c fiber.Ctx) bool

IsAdmin verifica se o usuário atual é administrador

func IsAuthenticated

func IsAuthenticated(c fiber.Ctx) bool

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

func TenantBasedKeyGenerator(c fiber.Ctx) string

TenantBasedKeyGenerator gera chave baseada no tenant (para multi-tenant)

func UserBasedKeyGenerator

func UserBasedKeyGenerator(c fiber.Ctx) string

UserBasedKeyGenerator gera chave baseada no usuário autenticado

func ValidateCountLimit

func ValidateCountLimit(estimatedCount int) error

ValidateCountLimit valida se o count está dentro dos limites permitidos

func ValidateCountParameter

func ValidateCountParameter(params map[string]string) error

ValidateCountParameter valida o parâmetro $count em uma URL

func ValidateCountValue

func ValidateCountValue(count string) error

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

func ValidateJWT(tokenString string, config ...*JWTConfig) (jwt.MapClaims, error)

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

func ValidateSkipValue(skip int) error

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"
	AuditOpUnauthorized AuditOperation = "UNAUTHORIZED"
)

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) Create

func (s *BaseEntityService) Create(ctx context.Context, entity any) (any, error)

Create cria uma nova entidade

func (*BaseEntityService) Delete

func (s *BaseEntityService) Delete(ctx context.Context, keys map[string]any) error

Delete remove uma entidade

func (*BaseEntityService) Get

func (s *BaseEntityService) Get(ctx context.Context, keys map[string]any) (any, error)

Get recupera uma entidade específica pelas 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

func (*BaseEntityService) Update

func (s *BaseEntityService) Update(ctx context.Context, keys map[string]any, entity any) (any, error)

Update atualiza uma entidade existente

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) BeginTx

func (p *BaseProvider) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

BeginTx inicia uma nova transação

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) Close

func (p *BaseProvider) Close() error

Close fecha a conexão com o banco

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

type BasicAuthConfig struct {
	Users map[string]string // username -> password
	Realm string
}

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

type Bool struct {
	Val   bool
	Valid bool
}

Bool representa um bool que pode ser null

func NewBool

func NewBool(value bool) Bool

NewBool cria um novo Bool válido

func NullBool

func NullBool() Bool

NullBool cria um Bool null

func (Bool) MarshalJSON

func (n Bool) MarshalJSON() ([]byte, error)

MarshalJSON implementa json.Marshaler

func (*Bool) Scan

func (n *Bool) Scan(value interface{}) error

Scan implementa sql.Scanner

func (*Bool) UnmarshalJSON

func (n *Bool) UnmarshalJSON(data []byte) error

UnmarshalJSON implementa json.Unmarshaler

func (Bool) Value

func (n Bool) Value() (driver.Value, error)

Value implementa driver.Valuer

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

type ComputeItem struct {
	Expression string
	Alias      string
}

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

type EntityCacheItem struct {
	Entity    any
	Key       string
	CachedAt  time.Time
	IsChanged bool
}

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"`
	Navigation []NavigationPropertyMetadata `json:"navigation,omitempty"`
}

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

func LoadEnvConfig() (*EnvConfig, error)

LoadEnvConfig carrega configurações do arquivo .env

func LoadEnvOrDefault

func LoadEnvOrDefault() (*EnvConfig, error)

LoadEnvOrDefault carrega configurações do .env ou retorna configurações padrão

func (*EnvConfig) BuildConnectionString

func (c *EnvConfig) BuildConnectionString() string

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

type EventHandler interface {
	Handle(args EventArgs) error
}

EventHandler representa um handler de evento

type EventHandlerFunc

type EventHandlerFunc func(args EventArgs) error

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
	ExpandTokenNav
	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

func (p *ExpressionParser) InfixToPostfix(ctx context.Context, tokens []*Token) ([]*Token, error)

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

func (p *ExpressionParser) PostfixToTree(ctx context.Context, postfix []*Token) (*ParseNode, error)

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

type Float64 struct {
	Val   float64
	Valid bool
}

Float64 representa um float64 que pode ser null

func NewFloat64

func NewFloat64(value float64) Float64

NewFloat64 cria um novo Float64 válido

func NullFloat64

func NullFloat64() Float64

NullFloat64 cria um Float64 null

func (Float64) MarshalJSON

func (n Float64) MarshalJSON() ([]byte, error)

MarshalJSON implementa json.Marshaler

func (*Float64) Scan

func (n *Float64) Scan(value interface{}) error

Scan implementa sql.Scanner

func (*Float64) UnmarshalJSON

func (n *Float64) UnmarshalJSON(data []byte) error

UnmarshalJSON implementa json.Unmarshaler

func (Float64) Value

func (n Float64) Value() (driver.Value, error)

Value implementa driver.Valuer

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

type GoDataFilterQuery struct {
	Tree     *ParseNode
	RawValue string
}

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

type GoDataSearchQuery struct {
	Tree     *ParseNode
	RawValue string
}

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

type Int64 struct {
	Val   int64
	Valid bool
}

Int64 representa um int64 que pode ser null

func NewInt64

func NewInt64(value int64) Int64

NewInt64 cria um novo Int64 válido

func NullInt64

func NullInt64() Int64

NullInt64 cria um Int64 null

func (Int64) MarshalJSON

func (n Int64) MarshalJSON() ([]byte, error)

MarshalJSON implementa json.Marshaler

func (*Int64) Scan

func (n *Int64) Scan(value interface{}) error

Scan implementa sql.Scanner

func (*Int64) UnmarshalJSON

func (n *Int64) UnmarshalJSON(data []byte) error

UnmarshalJSON implementa json.Unmarshaler

func (Int64) Value

func (n Int64) Value() (driver.Value, error)

Value implementa driver.Valuer

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

func (s *MultiTenantEntityService) Create(ctx context.Context, entity any) (any, error)

Create cria uma nova entidade usando o provider apropriado

func (*MultiTenantEntityService) Delete

func (s *MultiTenantEntityService) Delete(ctx context.Context, keys map[string]any) error

Delete remove uma 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

func (s *MultiTenantEntityService) Get(ctx context.Context, keys map[string]any) (any, error)

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

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

func NewNamedArgs(dialect string) *NamedArgs

NewNamedArgs cria uma nova instância de NamedArgs

func (*NamedArgs) AddArg

func (na *NamedArgs) AddArg(value interface{}) string

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 struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

NavigationLink representa um link de navegação OData

type NavigationPropertyMetadata struct {
	Name         string `json:"name"`
	Type         string `json:"type"`
	IsCollection bool   `json:"isCollection"`
	Partner      string `json:"partner,omitempty"`
}

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 NodeMap

type NodeMap map[string]string

NodeMap mapeia operadores OData para SQL

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

func (om *ObjectManager) ExecuteQuery(query string, args ...any) (*sql.Rows, error)

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:"-"`
	NavigationLinks []NavigationLink  `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:"-"`
	NavigationLinks []ResponseNavigationLink `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 (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

type PaginationInfo struct {
	PageSize   int
	Offset     int
	HasTop     bool
	HasSkip    bool
	PageNumber int
}

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 ParseNode

type ParseNode struct {
	Token    *Token
	Children []*ParseNode
	Parent   *ParseNode
}

ParseNode representa um nó na árvore de parse

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
	NavigationPath string                 // Caminho hierárquico (ex: "Itens", "Itens.Produtos")
	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

type PrepareMap map[string]string

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
	IsNavigation bool
	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

type QueryParseError struct {
	Message string
	Query   string
}

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

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop para o rate limiter e limpa recursos

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 struct {
	Name string `json:"-"`
	URL  string `json:"-"`
}

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) Add

func (s *Server) Add(methods []string, path string, handlers ...fiber.Handler) fiber.Router

Add adiciona uma rota com método customizado com prefixo automático

func (*Server) All

func (s *Server) All(path string, handlers ...fiber.Handler) fiber.Router

All registra rota para todos os métodos HTTP com prefixo automático

func (*Server) ApplyConfig

func (s *Server) ApplyConfig(config *ServerConfig) *Server

ApplyConfig aplica uma configuração completa ao servidor

func (*Server) AutoRegisterEntities

func (s *Server) AutoRegisterEntities(entities map[string]interface{}) error

AutoRegisterEntities registra múltiplas entidades automaticamente

func (*Server) CheckEntityReadOnly

func (s *Server) CheckEntityReadOnly(entityName string, method string) fiber.Handler

CheckEntityReadOnly verifica se a entidade é apenas leitura

func (*Server) DatabaseMiddleware

func (s *Server) DatabaseMiddleware() fiber.Handler

DatabaseMiddleware middleware que adiciona conexão de banco no contexto

func (*Server) Delete

func (s *Server) Delete(path string, handlers ...fiber.Handler) fiber.Router

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

func (s *Server) DisableRateLimit() *Server

DisableRateLimit desabilita rate limiting

func (*Server) GenerateJWT

func (s *Server) GenerateJWT(claims jwt.MapClaims, config ...*JWTConfig) (string, error)

GenerateJWT gera um token JWT (wrapper do método do servidor para compatibilidade)

func (*Server) GenerateRefreshToken

func (s *Server) GenerateRefreshToken(claims jwt.MapClaims, config ...*JWTConfig) (string, error)

GenerateRefreshToken gera um refresh token (wrapper do método do servidor para compatibilidade)

func (*Server) Get

func (s *Server) Get(path string, handlers ...fiber.Handler) fiber.Router

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

func (s *Server) GetAddress() string

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

func (s *Server) GetHandler() *fiber.App

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) GetRouter

func (s *Server) GetRouter() *fiber.App

GetRouter retorna o router do servidor

func (*Server) Group

func (s *Server) Group(prefix string, handlers ...fiber.Handler) fiber.Router

Group cria grupo de rotas

func (*Server) HandleBatch

func (s *Server) HandleBatch(c fiber.Ctx) error

HandleBatch é o handler para requisições $batch

func (*Server) Head

func (s *Server) Head(path string, handlers ...fiber.Handler) fiber.Router

Head registra rota HEAD com prefixo automático

func (*Server) Install

func (s *Server) Install() error

Install instala o servidor como serviço do sistema

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning retorna se o servidor está em execução

func (*Server) IsRunningAsService

func (s *Server) IsRunningAsService() bool

IsRunningAsService verifica se o processo está rodando como serviço do sistema

func (*Server) MultiTenantHealthCheck

func (s *Server) MultiTenantHealthCheck() fiber.Handler

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

func (s *Server) NewRouterJWTAuth(config ...*JWTConfig) fiber.Handler

NewRouterJWTAuth retorna middleware JWT Carrega config do .env se não fornecido

func (*Server) OnEntityDeleted

func (s *Server) OnEntityDeleted(entityName string, handler func(args EventArgs) error)

OnEntityDeleted registra um handler para o evento EntityDeleted

func (*Server) OnEntityDeletedGlobal

func (s *Server) OnEntityDeletedGlobal(handler func(args EventArgs) error)

OnEntityDeletedGlobal registra um handler global para o evento EntityDeleted

func (*Server) OnEntityDeleting

func (s *Server) OnEntityDeleting(entityName string, handler func(args EventArgs) error)

OnEntityDeleting registra um handler para o evento EntityDeleting

func (*Server) OnEntityDeletingGlobal

func (s *Server) OnEntityDeletingGlobal(handler func(args EventArgs) error)

OnEntityDeletingGlobal registra um handler global para o evento EntityDeleting

func (*Server) OnEntityError

func (s *Server) OnEntityError(entityName string, handler func(args EventArgs) error)

OnEntityError registra um handler para o evento EntityError

func (*Server) OnEntityErrorGlobal

func (s *Server) OnEntityErrorGlobal(handler func(args EventArgs) error)

OnEntityErrorGlobal registra um handler global para o evento EntityError

func (*Server) OnEntityGet

func (s *Server) OnEntityGet(entityName string, handler func(args EventArgs) error)

OnEntityGet registra um handler para o evento EntityGet

func (*Server) OnEntityGetGlobal

func (s *Server) OnEntityGetGlobal(handler func(args EventArgs) error)

OnEntityGetGlobal registra um handler global para o evento EntityGet

func (*Server) OnEntityInserted

func (s *Server) OnEntityInserted(entityName string, handler func(args EventArgs) error)

OnEntityInserted registra um handler para o evento EntityInserted

func (*Server) OnEntityInsertedGlobal

func (s *Server) OnEntityInsertedGlobal(handler func(args EventArgs) error)

OnEntityInsertedGlobal registra um handler global para o evento EntityInserted

func (*Server) OnEntityInserting

func (s *Server) OnEntityInserting(entityName string, handler func(args EventArgs) error)

OnEntityInserting registra um handler para o evento EntityInserting

func (*Server) OnEntityInsertingGlobal

func (s *Server) OnEntityInsertingGlobal(handler func(args EventArgs) error)

OnEntityInsertingGlobal registra um handler global para o evento EntityInserting

func (*Server) OnEntityList

func (s *Server) OnEntityList(entityName string, handler func(args EventArgs) error)

OnEntityList registra um handler para o evento EntityList

func (*Server) OnEntityListGlobal

func (s *Server) OnEntityListGlobal(handler func(args EventArgs) error)

OnEntityListGlobal registra um handler global para o evento EntityList

func (*Server) OnEntityModified

func (s *Server) OnEntityModified(entityName string, handler func(args EventArgs) error)

OnEntityModified registra um handler para o evento EntityModified

func (*Server) OnEntityModifiedGlobal

func (s *Server) OnEntityModifiedGlobal(handler func(args EventArgs) error)

OnEntityModifiedGlobal registra um handler global para o evento EntityModified

func (*Server) OnEntityModifying

func (s *Server) OnEntityModifying(entityName string, handler func(args EventArgs) error)

OnEntityModifying registra um handler para o evento EntityModifying

func (*Server) OnEntityModifyingGlobal

func (s *Server) OnEntityModifyingGlobal(handler func(args EventArgs) error)

OnEntityModifyingGlobal registra um handler global para o evento EntityModifying

func (*Server) Options

func (s *Server) Options(path string, handlers ...fiber.Handler) fiber.Router

Options registra rota OPTIONS com prefixo automático

func (*Server) Patch

func (s *Server) Patch(path string, handlers ...fiber.Handler) fiber.Router

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

func (s *Server) PayloadLoggerMiddleware() fiber.Handler

PayloadLoggerMiddleware retorna um middleware que loga request e response payloads quando habilitado

func (*Server) Post

func (s *Server) Post(path string, handlers ...fiber.Handler) fiber.Router

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

func (s *Server) Put(path string, handlers ...fiber.Handler) fiber.Router

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

func (s *Server) RateLimitMiddleware() fiber.Handler

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

func (s *Server) RequireEntityAuth(entityName string) fiber.Handler

RequireEntityAuth aplica middleware de autenticação baseado na configuração da entidade

func (*Server) RequireTenant

func (s *Server) RequireTenant(allowedTenants ...string) fiber.Handler

RequireTenant middleware que requer um tenant específico

func (*Server) Restart

func (s *Server) Restart() error

Restart reinicia o serviço do sistema

func (*Server) SetAllowedHeaders

func (s *Server) SetAllowedHeaders(headers []string) *Server

SetAllowedHeaders permite configurar headers permitidos para CORS

func (*Server) SetAllowedMethods

func (s *Server) SetAllowedMethods(methods []string) *Server

SetAllowedMethods permite configurar métodos HTTP permitidos para CORS

func (*Server) SetAllowedOrigins

func (s *Server) SetAllowedOrigins(origins []string) *Server

SetAllowedOrigins permite configurar origens permitidas para CORS

func (*Server) SetAuditLog

func (s *Server) SetAuditLog(enabled bool, logType string) *Server

SetAuditLog permite configurar audit logging

func (*Server) SetCORS

func (s *Server) SetCORS(enabled bool) *Server

SetCORS permite habilitar/desabilitar CORS

func (*Server) SetEnableLogging

func (s *Server) SetEnableLogging(enabled bool) *Server

SetEnableLogging permite habilitar/desabilitar logging

func (*Server) SetHost

func (s *Server) SetHost(host string) *Server

SetHost permite sobrescrever o host do servidor

func (*Server) SetLogLevel

func (s *Server) SetLogLevel(level string) *Server

SetLogLevel permite configurar o nível de log

func (*Server) SetMaxRequestSize

func (s *Server) SetMaxRequestSize(size int64) *Server

SetMaxRequestSize permite configurar o tamanho máximo de requisição

func (*Server) SetPort

func (s *Server) SetPort(port int) *Server

SetPort permite sobrescrever a porta do servidor

func (*Server) SetProvider

func (s *Server) SetProvider(provider DatabaseProvider) *Server

SetProvider permite trocar o provider de banco de dados

func (*Server) SetRateLimit

func (s *Server) SetRateLimit(requestsPerMinute, burstSize int) *Server

SetRateLimit permite configurar rate limiting

func (*Server) SetRateLimitConfig

func (s *Server) SetRateLimitConfig(config *RateLimitConfig)

SetRateLimitConfig configura o rate limiter do servidor

func (*Server) SetRoutePrefix

func (s *Server) SetRoutePrefix(prefix string) *Server

SetRoutePrefix permite sobrescrever o prefixo das rotas

func (*Server) SetSecurityHeaders

func (s *Server) SetSecurityHeaders(enabled bool) *Server

SetSecurityHeaders permite habilitar/desabilitar security headers

func (*Server) SetShutdownTimeout

func (s *Server) SetShutdownTimeout(timeout time.Duration) *Server

SetShutdownTimeout permite configurar o timeout de shutdown

func (*Server) SetTLS

func (s *Server) SetTLS(certFile, keyFile string) *Server

SetTLS permite configurar certificados TLS

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown para o servidor gracefully

func (*Server) Start

func (s *Server) Start() error

Start inicia o servidor HTTP Detecta automaticamente se deve executar como serviço ou normalmente

func (*Server) Status

func (s *Server) Status() (service.Status, error)

Status retorna o status do serviço do sistema

func (*Server) Stop

func (s *Server) Stop() error

Stop para o servidor gracefully Unifica StopService e Shutdown em um único método

func (*Server) TenantInfo

func (s *Server) TenantInfo() fiber.Handler

TenantInfo middleware que adiciona informações do tenant no contexto

func (*Server) TenantMiddleware

func (s *Server) TenantMiddleware() fiber.Handler

TenantMiddleware middleware para identificação de tenant

func (*Server) TenantRateLimitMiddleware

func (s *Server) TenantRateLimitMiddleware(requestsPerMinute int) fiber.Handler

TenantRateLimitMiddleware middleware para limitar requests por tenant

func (*Server) TenantStatsMiddleware

func (s *Server) TenantStatsMiddleware() fiber.Handler

TenantStatsMiddleware middleware para coletar estatísticas por tenant

func (*Server) TenantSwitchMiddleware

func (s *Server) TenantSwitchMiddleware() fiber.Handler

TenantSwitchMiddleware middleware para permitir mudança de tenant em tempo de execução

func (*Server) Uninstall

func (s *Server) Uninstall() error

Uninstall remove o servidor como serviço do sistema

func (*Server) Use

func (s *Server) Use(args ...interface{}) fiber.Router

Use adiciona middleware global

func (*Server) ValidateJWT

func (s *Server) ValidateJWT(tokenString string, config ...*JWTConfig) (jwt.MapClaims, error)

ValidateJWT valida um token JWT (wrapper do método do servidor para compatibilidade)

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

func (*ServiceWrapper) Start

func (sw *ServiceWrapper) Start(svc service.Service) error

Start é chamado pelo gerenciador de serviços para iniciar o serviço Implementa a interface service.Interface

func (*ServiceWrapper) Stop

func (sw *ServiceWrapper) Stop(svc service.Service) error

Stop é chamado pelo gerenciador de serviços para parar o serviço Implementa a interface service.Interface

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

type String struct {
	Val   string
	Valid bool
}

String representa uma string que pode ser null

func NewString

func NewString(value string) String

NewString cria uma nova String válida

func NullString

func NullString() String

NullString cria uma String null

func (String) MarshalJSON

func (n String) MarshalJSON() ([]byte, error)

MarshalJSON implementa json.Marshaler

func (*String) Scan

func (n *String) Scan(value interface{}) error

Scan implementa sql.Scanner

func (*String) UnmarshalJSON

func (n *String) UnmarshalJSON(data []byte) error

UnmarshalJSON implementa json.Unmarshaler

func (String) Value

func (n String) Value() (driver.Value, error)

Value implementa driver.Valuer

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

type Time struct {
	Val   time.Time
	Valid bool
}

Time representa um time.Time que pode ser null

func NewTime

func NewTime(value time.Time) Time

NewTime cria um novo Time válido

func NullTime

func NullTime() Time

NullTime cria um Time null

func (Time) MarshalJSON

func (n Time) MarshalJSON() ([]byte, error)

MarshalJSON implementa json.Marshaler

func (*Time) Scan

func (n *Time) Scan(value interface{}) error

Scan implementa sql.Scanner

func (*Time) UnmarshalJSON

func (n *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implementa json.Unmarshaler

func (Time) Value

func (n Time) Value() (driver.Value, error)

Value implementa driver.Valuer

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 NewTokenQueue

func NewTokenQueue() *TokenQueue

NewTokenQueue cria uma nova fila de tokens

func (*TokenQueue) Dequeue

func (q *TokenQueue) Dequeue() *Token

Dequeue remove e retorna o token do início da fila

func (*TokenQueue) Empty

func (q *TokenQueue) Empty() bool

Empty verifica se a fila está vazia

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) Reset

func (q *TokenQueue) Reset()

Reset reinicia a fila

func (*TokenQueue) Size

func (q *TokenQueue) Size() int

Size retorna o tamanho da fila

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 NewTokenStack

func NewTokenStack() *TokenStack

NewTokenStack cria uma nova pilha de tokens

func (*TokenStack) Empty

func (s *TokenStack) Empty() bool

Empty verifica se a pilha está vazia

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

func (*TokenStack) Size

func (s *TokenStack) Size() int

Size retorna o tamanho 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

func (*Tokenizer) Add

func (t *Tokenizer) Add(pattern string, tokenType int)

Add adiciona um padrão de token ao tokenizer

func (*Tokenizer) Tokenize

func (t *Tokenizer) Tokenize(ctx context.Context, input string) ([]*Token, error)

Tokenize tokeniza uma string em tokens

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

func NewOptimizedURLParser(strictMode bool) *URLParser

NewOptimizedURLParser cria um novo parser otimizado (mantido para compatibilidade)

func NewURLParser

func NewURLParser() *URLParser

NewURLParser cria um novo parser de URL

func (*URLParser) CleanODataValue

func (up *URLParser) CleanODataValue(value string) string

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

func (up *URLParser) ExtractODataSystemParams(values url.Values) map[string]string

ExtractODataSystemParams extrai parâmetros do sistema OData ($filter, $orderby, etc.)

func (*URLParser) GetCacheStats

func (up *URLParser) GetCacheStats() (normalizeEntries, validateEntries, simpleEntries int)

GetCacheStats retorna estatísticas do cache

func (*URLParser) NormalizeODataQuery

func (up *URLParser) NormalizeODataQuery(query string) string

NormalizeODataQuery é um alias para NormalizeODataQueryFast para compatibilidade

func (*URLParser) NormalizeODataQueryFast

func (up *URLParser) NormalizeODataQueryFast(query string) string

NormalizeODataQueryFast normalização otimizada

func (*URLParser) ParseExpandValue

func (up *URLParser) ParseExpandValue(value string) (string, error)

ParseExpandValue faz parsing específico de valores $expand

func (*URLParser) ParseFilterValue

func (up *URLParser) ParseFilterValue(value string) (string, error)

ParseFilterValue faz parsing específico de valores $filter

func (*URLParser) ParseODataURL

func (up *URLParser) ParseODataURL(rawURL string) (*url.URL, url.Values, error)

ParseODataURL faz o parsing completo de uma URL OData

func (*URLParser) ParseQuery

func (up *URLParser) ParseQuery(rawQuery string) (url.Values, error)

ParseQuery é um alias para ParseQueryFast para compatibilidade

func (*URLParser) ParseQueryFast

func (up *URLParser) ParseQueryFast(rawQuery string) (url.Values, error)

ParseQueryFast faz parsing rápido usando url.Values padrão quando possível

func (*URLParser) ValidateODataQuery

func (up *URLParser) ValidateODataQuery(query string) error

ValidateODataQuery é um alias para ValidateODataQueryFast para compatibilidade

func (*URLParser) ValidateODataQueryFast

func (up *URLParser) ValidateODataQueryFast(query string) error

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

Jump to

Keyboard shortcuts

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