Documentation
¶
Overview ¶
Package query provides a typed client for the Dynatrace DQL Query API (/platform/storage/query/v1/).
It supports synchronous and asynchronous query execution with automatic polling, query verification, and cancellation.
Index ¶
- Constants
- type AnalysisTimeframe
- type Approximations
- type BucketContribution
- type ColumnType
- type ColumnTypes
- type Contributions
- type ErrorResponse
- type ExecuteAndPollOptions
- type ExecuteRequest
- type FilterSegmentRef
- type FilterSegmentVariable
- type GrailMetadata
- type Handler
- func (h *Handler) Cancel(ctx context.Context, requestToken string) error
- func (h *Handler) Execute(ctx context.Context, req ExecuteRequest) (*Response, error)
- func (h *Handler) ExecuteAndPoll(ctx context.Context, req ExecuteRequest, onUnauthorized func() (string, error)) (*Response, error)
- func (h *Handler) ExecuteAndPollStream(ctx context.Context, req ExecuteRequest, opts ExecuteAndPollOptions, ...) (*Response, error)
- func (h *Handler) ExecuteAndPollWithOptions(ctx context.Context, req ExecuteRequest, opts ExecuteAndPollOptions) (*Response, error)
- func (h *Handler) ExecuteStream(ctx context.Context, req ExecuteRequest, ...) (*Response, error)
- func (h *Handler) Poll(ctx context.Context, requestToken string, timeoutMs int64, enrich bool) (*Response, error)
- func (h *Handler) PollStream(ctx context.Context, requestToken string, timeoutMs int64, enrich bool, ...) (*Response, error)
- func (h *Handler) Verify(ctx context.Context, req VerifyRequest) (*VerifyResponse, error)
- func (h *Handler) WithHeaders(headers map[string]string) *Handler
- type Metadata
- type MetricInfo
- type Notification
- type PollUpdate
- type Position
- type QueryError
- type Response
- type Result
- type StateError
- type SyntaxPosition
- type VerifyNotification
- type VerifyRequest
- type VerifyResponse
Constants ¶
const ( StateSucceeded = "SUCCEEDED" StateFailed = "FAILED" StateCancelled = "CANCELLED" StateResultGone = "RESULT_GONE" StateRunning = "RUNNING" StateNotStarted = "NOT_STARTED" )
Query states reported by the Query API.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AnalysisTimeframe ¶
type AnalysisTimeframe struct {
Start string `json:"start,omitempty"`
End string `json:"end,omitempty"`
}
AnalysisTimeframe represents the timeframe analyzed by the query.
type Approximations ¶
type Approximations []string
Approximations lists the ways Grail answered a different question than the query literally asked, e.g. "~ on content: substring match, not Grail's token match". A non-empty list means the result is approximate even though the query succeeded, so it must reach the caller rather than be dropped.
The shape observed from the query API is a list of strings (#415). Decoding is deliberately lenient anyway: this list lives inside the metadata block, and a strict decode that failed on an unexpected entry shape would fail the whole query response over an advisory field. A non-string entry keeps its "message" when it has one and its compact JSON text otherwise; a value that is not a list at all is kept as one entry if it is a string and ignored otherwise.
func (*Approximations) UnmarshalJSON ¶
func (a *Approximations) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler with the lenient decoding described on Approximations.
type BucketContribution ¶
type BucketContribution struct {
Name string `json:"name"`
Table string `json:"table"`
ScannedBytes int64 `json:"scannedBytes"`
MatchedRecordsRatio float64 `json:"matchedRecordsRatio"`
}
BucketContribution represents a single bucket's contribution to query results.
type ColumnType ¶
type ColumnType struct {
Type string `json:"type" yaml:"type"`
Types []ColumnTypes `json:"types,omitempty" yaml:"types,omitempty"`
}
ColumnType is the DQL type descriptor for a single column, e.g. {"type": "long"}. Array columns also carry the element types in Types, e.g. {"type": "array", "types": [{"indexRange": [0, 9], "mappings": {"element": {"type": "double"}}}]}.
type ColumnTypes ¶
type ColumnTypes struct {
// IndexRange is the [start, end] record index range (inclusive) that these
// mappings apply to.
IndexRange []int `json:"indexRange" yaml:"indexRange"`
// Mappings maps a column name to its DQL type descriptor.
Mappings map[string]ColumnType `json:"mappings" yaml:"mappings"`
}
ColumnTypes describes the column types for a contiguous range of records, as returned by the DQL API when includeTypes is requested. The API groups records that share the same column type mappings under a single entry.
type Contributions ¶
type Contributions struct {
Buckets []BucketContribution `json:"buckets,omitempty"`
}
Contributions represents the bucket contributions for a query.
type ErrorResponse ¶
type ErrorResponse struct {
Error struct {
Message string `json:"message"`
Details struct {
ErrorType string `json:"errorType"`
ErrorMessage string `json:"errorMessage"`
Arguments []string `json:"arguments"`
// QueryString is the query as the backend parsed it; the
// syntax error position indexes into it.
QueryString string `json:"queryString"`
SyntaxErrorPosition *SyntaxPosition `json:"syntaxErrorPosition"`
} `json:"details"`
} `json:"error"`
}
ErrorResponse represents the structured error response from the DQL query API.
type ExecuteAndPollOptions ¶
type ExecuteAndPollOptions struct {
// to refresh an expired token. It must return the new bearer token. If nil,
// 401 errors are returned directly.
OnUnauthorized func() (string, error)
// OnUpdate, if set, is called with the current progress/preview whenever the
// query is still RUNNING — once for the initial response and once per poll.
// It is never called for a query that completes synchronously.
OnUpdate func(PollUpdate)
}
ExecuteAndPollOptions carries optional hooks for ExecuteAndPollWithOptions.
type ExecuteRequest ¶
type ExecuteRequest struct {
Query string `json:"query"`
RequestTimeoutMilliseconds int64 `json:"requestTimeoutMilliseconds,omitempty"`
MaxResultRecords int64 `json:"maxResultRecords,omitempty"`
MaxResultBytes int64 `json:"maxResultBytes,omitempty"`
DefaultScanLimitGbytes float64 `json:"defaultScanLimitGbytes,omitempty"`
DefaultSamplingRatio float64 `json:"defaultSamplingRatio,omitempty"`
FetchTimeoutSeconds int32 `json:"fetchTimeoutSeconds,omitempty"`
// PollingPromiseSeconds bounds the maximum gap, in seconds, between
// successive polls of an asynchronous query. If the client does not issue
// the next poll within this window after the previous response, the backend
// auto-cancels the query. Optional.
PollingPromiseSeconds int32 `json:"pollingPromiseSeconds,omitempty"`
EnablePreview bool `json:"enablePreview,omitempty"`
EnforceQueryConsumptionLimit bool `json:"enforceQueryConsumptionLimit,omitempty"`
IncludeTypes *bool `json:"includeTypes,omitempty"`
IncludeContributions *bool `json:"includeContributions,omitempty"`
DefaultTimeframeStart string `json:"defaultTimeframeStart,omitempty"`
DefaultTimeframeEnd string `json:"defaultTimeframeEnd,omitempty"`
Locale string `json:"locale,omitempty"`
Timezone string `json:"timezone,omitempty"`
FilterSegments []FilterSegmentRef `json:"filterSegments,omitempty"`
// EnrichMetricMetadata requests metric-catalogue enrichment of the response's
// metadata.metrics[] entries (displayName, description, unit). It is sent as the
// `enrich=metric-metadata` query-string parameter on both query:execute and
// query:poll — not in the request body — hence json:"-".
EnrichMetricMetadata bool `json:"-"`
}
ExecuteRequest represents a DQL query execution request body.
type FilterSegmentRef ¶
type FilterSegmentRef struct {
ID string `json:"id"`
Variables []FilterSegmentVariable `json:"variables,omitempty"`
}
FilterSegmentRef identifies a segment and optional variable bindings for query execution.
type FilterSegmentVariable ¶
FilterSegmentVariable defines a variable binding for a filter segment.
type GrailMetadata ¶
type GrailMetadata struct {
Query string `json:"query,omitempty"`
CanonicalQuery string `json:"canonicalQuery,omitempty"`
QueryID string `json:"queryId,omitempty"`
DQLVersion string `json:"dqlVersion,omitempty"`
Timezone string `json:"timezone,omitempty"`
Locale string `json:"locale,omitempty"`
ExecutionTimeMilliseconds int64 `json:"executionTimeMilliseconds,omitempty"`
ScannedRecords int64 `json:"scannedRecords,omitempty"`
ScannedBytes int64 `json:"scannedBytes,omitempty"`
ScannedDataPoints int64 `json:"scannedDataPoints,omitempty"`
Sampled bool `json:"sampled,omitempty"`
Approximations Approximations `json:"approximations,omitempty"`
Notifications []Notification `json:"notifications,omitempty"`
AnalysisTimeframe *AnalysisTimeframe `json:"analysisTimeframe,omitempty"`
Contributions *Contributions `json:"contributions,omitempty"`
}
GrailMetadata represents Grail-specific query execution metadata.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles DQL query execution against the Dynatrace Query API.
func NewHandler ¶
func NewHandler(c *httpclient.Client) *Handler
NewHandler creates a new query handler.
func (*Handler) Execute ¶
Execute submits a DQL query for execution. If the query completes synchronously the response contains the results directly. If the query is asynchronous (HTTP 202 or state RUNNING), the response contains a RequestToken for polling.
Execute accumulates the full result in memory; see ExecuteStream for a bounded-memory alternative.
func (*Handler) ExecuteAndPoll ¶
func (h *Handler) ExecuteAndPoll(ctx context.Context, req ExecuteRequest, onUnauthorized func() (string, error)) (*Response, error)
ExecuteAndPoll executes a DQL query and, if it returns asynchronously, polls until completion or context cancellation. If the context is cancelled during polling, a best-effort cancel is sent to the backend.
The optional onUnauthorized callback is invoked when a poll receives HTTP 401, allowing callers to refresh an expired token. It must return the new bearer token. If nil, 401 errors are returned directly.
func (*Handler) ExecuteAndPollStream ¶
func (h *Handler) ExecuteAndPollStream(ctx context.Context, req ExecuteRequest, opts ExecuteAndPollOptions, onRecord func(map[string]interface{}) error) (*Response, error)
ExecuteAndPollStream is ExecuteAndPoll with the terminal response's rows delivered to onRecord instead of accumulated, so peak memory does not grow with the result size. The returned Response carries state and metadata with Records / Result.Records left nil.
Rows belonging to a still-running response (the preview snapshots EnablePreview asks for) are not forwarded: a preview is a whole snapshot, not a delta, so forwarding one would deliver rows the final response repeats. They still reach OnUpdate as PollUpdate.Preview when the request set EnablePreview and OnUpdate is set, exactly as with ExecuteAndPollWithOptions; otherwise they are discarded as they decode.
func (*Handler) ExecuteAndPollWithOptions ¶
func (h *Handler) ExecuteAndPollWithOptions(ctx context.Context, req ExecuteRequest, opts ExecuteAndPollOptions) (*Response, error)
ExecuteAndPollWithOptions is ExecuteAndPoll with additional hooks (see ExecuteAndPollOptions), notably an OnUpdate callback for surfacing progress and preview results while the query is still running.
func (*Handler) ExecuteStream ¶
func (h *Handler) ExecuteStream(ctx context.Context, req ExecuteRequest, onRecord func(map[string]interface{}) error) (*Response, error)
ExecuteStream is Execute but decodes incrementally, calling onRecord per row instead of accumulating. Response.Records / Result.Records are always nil; onRecord may be nil to just discard rows.
func (*Handler) Poll ¶
func (h *Handler) Poll(ctx context.Context, requestToken string, timeoutMs int64, enrich bool) (*Response, error)
Poll polls for the results of an asynchronous query. The server holds the connection for up to timeoutMs milliseconds before returning. When enrich is true, the poll requests metric-metadata enrichment so the final SUCCEEDED response carries displayName/description/unit — it must match the enrichment requested on the originating execute call.
Like Execute, Poll accumulates the full result in memory; see PollStream for a bounded-memory alternative.
func (*Handler) PollStream ¶
func (h *Handler) PollStream(ctx context.Context, requestToken string, timeoutMs int64, enrich bool, onRecord func(map[string]interface{}) error) (*Response, error)
PollStream is Poll but streams like ExecuteStream — same onRecord/nil-Records contract.
func (*Handler) Verify ¶
func (h *Handler) Verify(ctx context.Context, req VerifyRequest) (*VerifyResponse, error)
Verify validates a DQL query without executing it.
type Metadata ¶
type Metadata struct {
Grail *GrailMetadata `json:"grail,omitempty"`
Metrics []MetricInfo `json:"metrics,omitempty"`
}
Metadata represents the metadata section of a DQL response.
type MetricInfo ¶
type MetricInfo struct {
MetricKey string `json:"metric.key,omitempty"`
FieldName string `json:"fieldName,omitempty"`
Aggregation string `json:"aggregation,omitempty"`
DisplayName string `json:"displayName,omitempty"`
Description string `json:"description,omitempty"`
Unit string `json:"unit,omitempty"`
}
MetricInfo describes a single metric referenced in a timeseries query result. It maps the DQL column name (FieldName) to the underlying metric descriptor. DisplayName, Description, and Unit are present only when the API returns metric catalogue data; they are absent for tenants or queries that do not populate them.
type Notification ¶
type Notification struct {
Severity string `json:"severity,omitempty"`
NotificationType string `json:"notificationType,omitempty"`
Message string `json:"message,omitempty"`
MessageFormat string `json:"messageFormat,omitempty"`
Arguments []string `json:"arguments,omitempty"`
}
Notification represents a notification/warning from query execution.
type PollUpdate ¶
type PollUpdate struct {
// Progress is the query's completion percentage (0-100) as reported by the
// backend. It may stay at 0 until the backend has a meaningful estimate.
Progress int
// Preview is a partial result snapshot. It is non-nil only when the request
// set EnablePreview and this poll carried preview records. Each preview is
// whole (not a delta to prior previews), so callers replace, never append.
Preview *Result
// ScannedBytes and ScannedRecords are the running scan totals reported by the
// backend for this poll. Grail populates and grows them on each poll of a
// mass-data query; they are 0 when the backend has not reported them (e.g. an
// early poll or a query type that does not scan Grail).
ScannedBytes int64
ScannedRecords int64
}
PollUpdate carries the state of a still-running query. It is delivered to the OnUpdate callback of ExecuteAndPollWithOptions on the initial RUNNING response and after each subsequent poll, letting callers render progress.
type QueryError ¶
type QueryError struct {
StatusCode int
Message string
ErrorType string
Detail string
Arguments []string
// Query is the query the backend parsed, and Position the offending span
// within it (1-based line/column, end inclusive). Both are empty when the
// backend reported no position, e.g. for errors that are not about the
// query text.
Query string
Position *SyntaxPosition
}
QueryError is a structured error from the DQL Query API.
func (*QueryError) Error ¶
func (e *QueryError) Error() string
type Response ¶
type Response struct {
State string `json:"state"`
RequestToken string `json:"requestToken,omitempty"`
Result *Result `json:"result,omitempty"`
Records []map[string]interface{} `json:"records,omitempty"` // backward compatibility
Progress int `json:"progress,omitempty"`
Metadata *Metadata `json:"metadata,omitempty"`
}
Response represents a DQL query response from execute or poll.
func (*Response) GetApproximations ¶
GetApproximations returns the approximations Grail reported for the result, checking both top-level and result-level metadata (in the same order as GetNotifications). Nil means the result is not approximate in any declared way.
func (*Response) GetMetadata ¶
func (r *Response) GetMetadata() *GrailMetadata
GetMetadata returns the Grail metadata from the response, checking both top-level and result-level metadata.
func (*Response) GetMetrics ¶
func (r *Response) GetMetrics() []MetricInfo
GetMetrics returns the metrics array from the response, checking both result-level and top-level metadata. Returns nil when no metrics are present (e.g., for non-timeseries queries).
func (*Response) GetNotifications ¶
func (r *Response) GetNotifications() []Notification
GetNotifications returns notifications from the response, checking both top-level and result-level metadata.
func (*Response) GetRecords ¶
GetRecords returns the result records, checking both the Result wrapper and the top-level Records field (backward compatibility).
func (*Response) GetTypes ¶
func (r *Response) GetTypes() []ColumnTypes
GetTypes returns the per-column DQL type mappings from the result section, as populated when the request set includeTypes. Returns nil when the API did not include type information.
type Result ¶
type Result struct {
Records []map[string]interface{} `json:"records"`
Types []ColumnTypes `json:"types,omitempty"`
Metadata *Metadata `json:"metadata,omitempty"`
}
Result represents the result section of a DQL response.
type StateError ¶
type StateError struct {
State string
// TimedOut reports that the query never left State before the poll
// deadline expired. It may well still be running on the backend, so the
// message must not claim the state itself was terminal.
TimedOut bool
}
StateError reports a query that did not end in SUCCEEDED: a known failure state, or a state dtctl does not recognize.
What a live tenant actually does, probed against the Query API: it answers RUNNING, NOT_STARTED and SUCCEEDED as states, and reports failures over HTTP instead — 400 with a typed DQL error for a query it rejects, 410 QUERY_GONE for a result that expired, was consumed, or was cancelled. A scan limit, a fetch timeout and an oversized result all come back as a truncated success rather than as a failure. FAILED and CANCELLED were never observed as states, so the branches for them are the forward-compatible half of this type: the states the API documents, handled in case they do appear.
func (*StateError) Error ¶
func (e *StateError) Error() string
type SyntaxPosition ¶
type SyntaxPosition struct {
Start *Position `json:"start,omitempty"`
End *Position `json:"end,omitempty"`
}
SyntaxPosition represents the position of a syntax issue in a query.
type VerifyNotification ¶
type VerifyNotification struct {
Severity string `json:"severity"`
NotificationType string `json:"notificationType"`
Message string `json:"message"`
SyntaxPosition *SyntaxPosition `json:"syntaxPosition,omitempty"`
}
VerifyNotification represents a notification from query verification.
type VerifyRequest ¶
type VerifyRequest struct {
Query string `json:"query"`
GenerateCanonicalQuery bool `json:"generateCanonicalQuery,omitempty"`
Timezone string `json:"timezone,omitempty"`
Locale string `json:"locale,omitempty"`
}
VerifyRequest represents a DQL query verification request body.
type VerifyResponse ¶
type VerifyResponse struct {
Valid bool `json:"valid"`
CanonicalQuery string `json:"canonicalQuery,omitempty"`
Notifications []VerifyNotification `json:"notifications,omitempty"`
}
VerifyResponse represents a DQL query verification response.