query

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CommonFields = map[string]func(ctx context.Context, tx *gorm.DB, val string) (*gorm.DB, error){
	"limit": func(ctx context.Context, tx *gorm.DB, val string) (*gorm.DB, error) {
		if i, err := strconv.Atoi(val); err == nil {
			return tx.Limit(i), nil
		} else {
			return nil, err
		}
	},
	"sort": func(ctx context.Context, tx *gorm.DB, sort string) (*gorm.DB, error) {
		return tx.Order(clause.OrderByColumn{Column: clause.Column{Name: sort}}), nil
	},
	"offset": func(ctx context.Context, tx *gorm.DB, val string) (*gorm.DB, error) {
		if i, err := strconv.Atoi(val); err == nil {
			return tx.Offset(i), nil
		} else {
			return nil, err
		}
	},
}

CommonFields provides built-in query field handlers for common operations

View Source
var DateMapper = func(ctx context.Context, val string) (any, error) {
	if expr, err := datemath.Parse(val); err != nil {
		return nil, fmt.Errorf("invalid date '%s': %s", val, err)
	} else {
		return expr.Time(), nil
	}
}

DateMapper maps date expressions (including datemath like "now-7d") to actual time values

View Source
var JSONPathMapper = func(ctx context.Context, tx *gorm.DB, column string, op grammar.QueryOperator, path string, val string) *gorm.DB {
	if !slices.Contains([]grammar.QueryOperator{grammar.Eq, grammar.Neq}, op) {
		op = grammar.Eq
	}
	values := strings.Split(val, ",")
	for _, v := range values {
		tx = tx.Where(fmt.Sprintf(`TRIM(BOTH '"' from jsonb_path_query_first(%s, '$.%s')::TEXT) %s ?`, column, path, op), v)
	}
	return tx
}

JSONPathMapper handles JSONPath queries against JSONB columns

Functions

func FlushResourceSelectorCache

func FlushResourceSelectorCache()

FlushResourceSelectorCache flushes all resource selector caches

func OrQueries

func OrQueries(db *gorm.DB, queries ...*gorm.DB) *gorm.DB

OrQueries combines multiple gorm queries with OR logic

func ParseFilteringQuery

func ParseFilteringQuery(query string, decodeURL bool) (grammar.FilteringQuery, error)

ParseFilteringQuery parses a filtering query string

func QueryResourceSelectors

func QueryResourceSelectors[T any](
	ctx context.Context,
	queryModel QueryModel,
	selectColumns []string,
	limit int,
	clauses []clause.Expression,
	resourceSelectors ...types.ResourceSelector,
) ([]T, error)

QueryResourceSelectors queries a table using multiple resource selectors. It returns the combined results from all selectors, respecting the limit.

Example usage:

model := QueryModel{
    Table: "my_resources",
    Columns: []string{"id", "name", "type"},
    HasTags: true,
}
results, err := QueryResourceSelectors[MyResource](ctx, model, []string{"id", "name"}, 100, nil, selectors...)

func SetResourceSelectorClause

func SetResourceSelectorClause(
	ctx context.Context,
	resourceSelector types.ResourceSelector,
	query *gorm.DB,
	queryModel QueryModel,
) (*gorm.DB, error)

SetResourceSelectorClause applies a ResourceSelector to a GORM query. The caller must provide a QueryModel that defines the table structure and capabilities.

Returns the modified query and any error encountered.

Types

type QueryModel

type QueryModel struct {
	// Table name
	Table string

	// Custom functions to map fields to clauses
	// Example: map["custom_field"] = func(ctx, tx, val) { ... custom query logic ... }
	Custom map[string]func(ctx context.Context, tx *gorm.DB, val string) (*gorm.DB, error)

	// List of jsonb columns that store a map.
	// These columns can be addressed using dot notation to access the JSON fields directly
	// Example: tags.cluster or tags.namespace.
	JSONMapColumns []string

	// List of columns that can be addressed on the search query.
	// Any other fields will be treated as a property lookup.
	Columns []string

	// Alias maps fields from the search query to the table columns
	// Example: map["created"] = "created_at"
	Aliases map[string]string

	// True when the table has a "tags" column
	HasTags bool

	// True when the table has a "labels" column
	HasLabels bool

	// True when the table has properties column
	HasProperties bool

	// FieldMapper maps the value of these fields
	// Example: map["created_at"] = DateMapper
	FieldMapper map[string]func(ctx context.Context, id string) (any, error)
}

QueryModel defines the structure and capabilities of a queryable table/resource. Consumers can create their own QueryModel instances for their specific tables.

func (QueryModel) Apply

Apply processes a query field and converts it to GORM clauses. It handles: - Field aliases - Field value mapping (via FieldMapper) - Common field operations (limit, sort, offset) - Custom field handlers - JSON path queries - Property filtering Returns the modified transaction, clauses to add, and any error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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