@grafana/plugin-ui 0.17.9 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +97 -2934
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +19 -23
- package/dist/esm/async-query-data/DatasourceWithAsyncBackend.js +2 -2
- package/dist/esm/async-query-data/DatasourceWithAsyncBackend.js.map +1 -1
- package/dist/esm/components/DataSourcePicker/DataSourcePicker.js +88 -87
- package/dist/esm/components/DataSourcePicker/DataSourcePicker.js.map +1 -1
- package/dist/esm/datasource/SqlDatasource.js +5 -3
- package/dist/esm/datasource/SqlDatasource.js.map +1 -1
- package/dist/esm/index.d.ts +19 -23
- package/dist/esm/index.js +0 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js +2 -2
- package/dist/esm/node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js.map +1 -1
- package/package.json +5 -2
- package/dist/esm/_virtual/index.js +0 -6
- package/dist/esm/_virtual/index.js.map +0 -1
- package/dist/esm/_virtual/re.js +0 -4
- package/dist/esm/_virtual/re.js.map +0 -1
- package/dist/esm/components/ConfigEditor/DatasourceConfigWizard/resolvePluginName.js +0 -30
- package/dist/esm/components/ConfigEditor/DatasourceConfigWizard/resolvePluginName.js.map +0 -1
- package/dist/esm/node_modules/semver/classes/comparator.js +0 -160
- package/dist/esm/node_modules/semver/classes/comparator.js.map +0 -1
- package/dist/esm/node_modules/semver/classes/range.js +0 -595
- package/dist/esm/node_modules/semver/classes/range.js.map +0 -1
- package/dist/esm/node_modules/semver/classes/semver.js +0 -366
- package/dist/esm/node_modules/semver/classes/semver.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/clean.js +0 -20
- package/dist/esm/node_modules/semver/functions/clean.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/cmp.js +0 -71
- package/dist/esm/node_modules/semver/functions/cmp.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/coerce.js +0 -76
- package/dist/esm/node_modules/semver/functions/coerce.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/compare-build.js +0 -21
- package/dist/esm/node_modules/semver/functions/compare-build.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/compare-loose.js +0 -17
- package/dist/esm/node_modules/semver/functions/compare-loose.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/compare.js +0 -19
- package/dist/esm/node_modules/semver/functions/compare.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/diff.js +0 -72
- package/dist/esm/node_modules/semver/functions/diff.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/eq.js +0 -17
- package/dist/esm/node_modules/semver/functions/eq.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/gt.js +0 -17
- package/dist/esm/node_modules/semver/functions/gt.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/gte.js +0 -17
- package/dist/esm/node_modules/semver/functions/gte.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/inc.js +0 -33
- package/dist/esm/node_modules/semver/functions/inc.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/lt.js +0 -17
- package/dist/esm/node_modules/semver/functions/lt.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/lte.js +0 -17
- package/dist/esm/node_modules/semver/functions/lte.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/major.js +0 -17
- package/dist/esm/node_modules/semver/functions/major.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/minor.js +0 -17
- package/dist/esm/node_modules/semver/functions/minor.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/neq.js +0 -17
- package/dist/esm/node_modules/semver/functions/neq.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/parse.js +0 -30
- package/dist/esm/node_modules/semver/functions/parse.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/patch.js +0 -17
- package/dist/esm/node_modules/semver/functions/patch.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/prerelease.js +0 -20
- package/dist/esm/node_modules/semver/functions/prerelease.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/rcompare.js +0 -17
- package/dist/esm/node_modules/semver/functions/rcompare.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/rsort.js +0 -17
- package/dist/esm/node_modules/semver/functions/rsort.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/satisfies.js +0 -24
- package/dist/esm/node_modules/semver/functions/satisfies.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/sort.js +0 -17
- package/dist/esm/node_modules/semver/functions/sort.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/truncate.js +0 -62
- package/dist/esm/node_modules/semver/functions/truncate.js.map +0 -1
- package/dist/esm/node_modules/semver/functions/valid.js +0 -20
- package/dist/esm/node_modules/semver/functions/valid.js.map +0 -1
- package/dist/esm/node_modules/semver/index.js +0 -146
- package/dist/esm/node_modules/semver/index.js.map +0 -1
- package/dist/esm/node_modules/semver/internal/constants.js +0 -47
- package/dist/esm/node_modules/semver/internal/constants.js.map +0 -1
- package/dist/esm/node_modules/semver/internal/debug.js +0 -21
- package/dist/esm/node_modules/semver/internal/debug.js.map +0 -1
- package/dist/esm/node_modules/semver/internal/identifiers.js +0 -39
- package/dist/esm/node_modules/semver/internal/identifiers.js.map +0 -1
- package/dist/esm/node_modules/semver/internal/lrucache.js +0 -52
- package/dist/esm/node_modules/semver/internal/lrucache.js.map +0 -1
- package/dist/esm/node_modules/semver/internal/parse-options.js +0 -27
- package/dist/esm/node_modules/semver/internal/parse-options.js.map +0 -1
- package/dist/esm/node_modules/semver/internal/re.js +0 -238
- package/dist/esm/node_modules/semver/internal/re.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/gtr.js +0 -18
- package/dist/esm/node_modules/semver/ranges/gtr.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/intersects.js +0 -21
- package/dist/esm/node_modules/semver/ranges/intersects.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/ltr.js +0 -18
- package/dist/esm/node_modules/semver/ranges/ltr.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/max-satisfying.js +0 -40
- package/dist/esm/node_modules/semver/ranges/max-satisfying.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/min-satisfying.js +0 -39
- package/dist/esm/node_modules/semver/ranges/min-satisfying.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/min-version.js +0 -77
- package/dist/esm/node_modules/semver/ranges/min-version.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/outside.js +0 -101
- package/dist/esm/node_modules/semver/ranges/outside.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/simplify.js +0 -62
- package/dist/esm/node_modules/semver/ranges/simplify.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/subset.js +0 -264
- package/dist/esm/node_modules/semver/ranges/subset.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/to-comparators.js +0 -22
- package/dist/esm/node_modules/semver/ranges/to-comparators.js.map +0 -1
- package/dist/esm/node_modules/semver/ranges/valid.js +0 -25
- package/dist/esm/node_modules/semver/ranges/valid.js.map +0 -1
package/dist/cjs/index.d.cts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import React, { ComponentProps,
|
|
1
|
+
import React, { ComponentProps, ReactElement, ReactNode, Component, ErrorInfo, PureComponent, FunctionComponent, HTMLProps } from 'react';
|
|
2
2
|
import { Input, Segment as Segment$1, monacoTypes, Monaco, ButtonProps, Field, PopoverContent, Switch, SelectCommonProps, InlineLabel } from '@grafana/ui';
|
|
3
|
-
import { DataSourceInstanceSettings,
|
|
4
|
-
import { DataSourceSrv, DataSourceWithBackend, TemplateSrv } from '@grafana/runtime';
|
|
3
|
+
import { DataSourceInstanceSettings, DataSourceJsonData, VariableSuggestion, SelectableValue, TimeRange, DataFrame, MetricFindValue, ThemeSpacingTokens, ScopedVars, VariableModel, DataFrameView, QueryEditorProps as QueryEditorProps$1, DataSourceSettings, RegistryItem, DataSourceApi, Registry, DataQuery as DataQuery$1, PanelData, DataQueryRequest, DataQueryResponse, LoadingState } from '@grafana/data';
|
|
5
4
|
import { JsonTree } from '@react-awesome-query-builder/ui';
|
|
6
5
|
import { DataQuery } from '@grafana/schema';
|
|
6
|
+
import { DataSourceWithBackend, TemplateSrv } from '@grafana/runtime';
|
|
7
7
|
import { SqlLanguage } from 'sql-formatter';
|
|
8
8
|
import { Grammar } from 'prismjs';
|
|
9
9
|
import { Observable } from 'rxjs';
|
|
@@ -46,8 +46,16 @@ interface DatePickerWithInputProps extends Omit<ComponentProps<typeof Input>, 'r
|
|
|
46
46
|
declare const DatePickerWithInput: (props: DatePickerWithInputProps) => React.JSX.Element;
|
|
47
47
|
|
|
48
48
|
interface Props$s {
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Receives the selected data source's list item (`uid`, `type`, `name`, `meta`). Call
|
|
51
|
+
* `getDataSourceInstanceSettings(ds.uid)` from `@grafana/plugin-compat` if you need the full settings.
|
|
52
|
+
*/
|
|
53
|
+
onChange: (ds: Pick<DataSourceInstanceSettings, 'uid' | 'type' | 'name' | 'meta'>) => void;
|
|
54
|
+
/**
|
|
55
|
+
* Reference to the selected data source, resolved the way Grafana does: uid, name, template variable or
|
|
56
|
+
* built-in. `null`/`undefined` resolves to the default data source.
|
|
57
|
+
*/
|
|
58
|
+
current?: string | null;
|
|
51
59
|
hideTextValue?: boolean;
|
|
52
60
|
onBlur?: () => void;
|
|
53
61
|
autoFocus?: boolean;
|
|
@@ -62,20 +70,7 @@ interface Props$s {
|
|
|
62
70
|
pluginId?: string;
|
|
63
71
|
noDefault?: boolean;
|
|
64
72
|
}
|
|
65
|
-
|
|
66
|
-
error?: string;
|
|
67
|
-
}
|
|
68
|
-
declare class DataSourcePicker extends PureComponent<Props$s, State$1> {
|
|
69
|
-
dataSourceSrv: DataSourceSrv;
|
|
70
|
-
static defaultProps: Partial<Props$s>;
|
|
71
|
-
state: State$1;
|
|
72
|
-
constructor(props: Props$s);
|
|
73
|
-
componentDidMount(): void;
|
|
74
|
-
onChange: (item: SelectableValue<string>) => void;
|
|
75
|
-
private getCurrentValue;
|
|
76
|
-
getDataSourceOptions(): Array<SelectableValue<string>>;
|
|
77
|
-
render(): React.JSX.Element;
|
|
78
|
-
}
|
|
73
|
+
declare function DataSourcePicker({ onChange, current: currentProp, hideTextValue, onBlur, autoFocus, openMenuOnFocus, placeholder, noDefault, }: Props$s): React.JSX.Element;
|
|
79
74
|
|
|
80
75
|
type DataLinkConfig = {
|
|
81
76
|
field: string;
|
|
@@ -778,6 +773,9 @@ declare abstract class SqlDatasource extends DataSourceWithBackend<SQLQuery, SQL
|
|
|
778
773
|
interpolateVariablesInQueries(queries: SQLQuery[], scopedVars: ScopedVars): SQLQuery[];
|
|
779
774
|
filterQuery(query: SQLQuery): boolean;
|
|
780
775
|
applyTemplateVariables(target: SQLQuery, scopedVars: ScopedVars): SQLQuery;
|
|
776
|
+
/**
|
|
777
|
+
* @deprecated `applyTemplateVariables` no longer calls this. Collapsing `''` to `'` breaks valid SQL string literals.
|
|
778
|
+
*/
|
|
781
779
|
clean(value: string): string;
|
|
782
780
|
metricFindQuery(query: string, optionalOptions?: MetricFindQueryOptions): Promise<MetricFindValue[]>;
|
|
783
781
|
runSql<T extends object>(query: string, options?: RunSQLOptions): Promise<DataFrameView<T>>;
|
|
@@ -1519,8 +1517,6 @@ declare function useHealthChecks(): {
|
|
|
1519
1517
|
retry: (uid: string) => void;
|
|
1520
1518
|
};
|
|
1521
1519
|
|
|
1522
|
-
declare function resolvePluginName(pluginType: string): string;
|
|
1523
|
-
|
|
1524
1520
|
type UseDatasourceSchemaResult = {
|
|
1525
1521
|
schema: DatasourceConfigSchema | null;
|
|
1526
1522
|
loading: boolean;
|
|
@@ -2016,5 +2012,5 @@ interface RequestLoopOptions<TQuery extends DataQuery$1 = DataQuery$1> {
|
|
|
2016
2012
|
*/
|
|
2017
2013
|
declare function getRequestLooper<T extends DataQuery$1 = DataQuery$1>(req: DataQueryRequest<T>, options: RequestLoopOptions<T>): Observable<DataQueryResponse>;
|
|
2018
2014
|
|
|
2019
|
-
export { AUTH_GROUP_IDS, AccessoryButton, AdvancedHttpSettings, Auth, AuthMethod, BINARY_OPERATIONS_KEY, CatalogSelector, CompletionItemInsertTextRule, CompletionItemKind, CompletionItemPriority, ConfigDescriptionLink, ConfigSection, ConfigSubSection, ConnectionSettings, CustomHeadersSettings, DataLink, DataLinks, DataSourceDescription, DataSourcePicker, DatasetSelector, DatasourceConfigWizard, DatasourceErrorBoundary, DatasourceWithAsyncBackend, DatePicker, DatePickerWithInput, DebounceInput, EditorField, EditorFieldGroup, EditorHeader, EditorList, EditorMode, EditorRow, EditorRows, EditorStack, EditorSwitch, FlexItem, GroupByRow, InlineSelect, InputGroup, LabelFilters, LinkedToken, MacroType, OperationExplainedBox, OperationList, OperationListExplained, OperationsEditorRow, OperatorType, QUERY_FORMAT_OPTIONS, QueryBuilderHints, QueryEditorMode, QueryEditorModeToggle, QueryEditorRow, QueryFormat, QueryHeaderSwitch, QueryModellerBase, QueryOptionGroup, ROOT_CONFIG_FIELDS, RawQuery, RunQueryButton, RunQueryButtons, SQLEditor, SQLEditorMode, SQLEditorTestUtils, SecureSocksProxyToggle, Segment, Space, SqlDatasource, SqlQueryEditor, StatementPosition, SuggestionKind, TLSSettings, TableSelector, TokenType, buildCelContext, buildCloneDatasourcePayload, buildCreateDatasourcePayload, buildUpdateDatasourcePayload, clearExpressionCache, computeVirtualFieldValues, convertLegacyAuthProps, datasourceToProvisioningYaml, evaluateCelDirect, evaluateCelExpression, evaluateComputedRead, evaluateDependsOn, extractFieldRefs, fetchConfigSchema, formKey, formatDate, formatYamlDiff, generateLLMHint, generateProvisioningTemplate, generateTroubleshootingFields, getConfigSchema, getRequestLooper, getStandardSQLCompletionProvider, getWatchedValue, language as grafanaStandardSQLLanguage, conf as grafanaStandardSQLLanguageConf, isAuthGroupId, isValidCelExpression, parseDependsOn, resolveActiveOverride, resolveGroups,
|
|
2020
|
-
export type { Aggregate, AllowedValuesValidationRule, Props$c as AuthProps, BaseFieldRef, BaseValidationRule, ColumnDefinition, ComputedMapping, ConfigField, ConfigGroup, CustomMeta, CustomValidationRule, DB, DataLinkConfig, DatasourceConfigSchema, DatasourceConfigWizardProps, DatasourceHealth, DatePickerProps, DatePickerWithInputProps, DebounceInputProps, DirectMapping, Expression, FieldEffect, FieldItemSchema, FieldKind, FieldOption, FieldOverride, FieldPack, FieldPackID, FieldPatch, FieldRelationship, FieldUI, FieldValidationRule, FormState, HealthState, IndexedPairMapping, Instruction, ItemCountValidationRule, LanguageCompletionProvider, LanguageDefinition, LengthValidationRule, MappingField, MetaDefinition, NameValue, PatternValidationRule, PositionContext, Props$s as Props, QueryBuilderLabelFilter, QueryBuilderOperation, QueryBuilderOperationDefinition, QueryBuilderOperationParamDef, QueryBuilderOperationParamEditorProps, QueryBuilderOperationParamValue, QueryEditorProps, QueryRowFilter, QueryStats, QueryWithDefaults, RAQBFieldTypes, RangeValidationRule, RelationshipType, RequestLoopOptions, ResolvedGroup, ResourceSelectorProps, ResponseParser, Role, RunQueryButtonsProps, RunningQueryInfo, SQLConnectionLimits, SQLExpression, SQLFilters, SQLMonarchLanguage, SQLOptions, SQLQuery, SQLSelectableValue, SchemaDefinition, SecureFieldState, SegmentProps, SqlQueryForInterpolation, SqlQueryModel,
|
|
2015
|
+
export { AUTH_GROUP_IDS, AccessoryButton, AdvancedHttpSettings, Auth, AuthMethod, BINARY_OPERATIONS_KEY, CatalogSelector, CompletionItemInsertTextRule, CompletionItemKind, CompletionItemPriority, ConfigDescriptionLink, ConfigSection, ConfigSubSection, ConnectionSettings, CustomHeadersSettings, DataLink, DataLinks, DataSourceDescription, DataSourcePicker, DatasetSelector, DatasourceConfigWizard, DatasourceErrorBoundary, DatasourceWithAsyncBackend, DatePicker, DatePickerWithInput, DebounceInput, EditorField, EditorFieldGroup, EditorHeader, EditorList, EditorMode, EditorRow, EditorRows, EditorStack, EditorSwitch, FlexItem, GroupByRow, InlineSelect, InputGroup, LabelFilters, LinkedToken, MacroType, OperationExplainedBox, OperationList, OperationListExplained, OperationsEditorRow, OperatorType, QUERY_FORMAT_OPTIONS, QueryBuilderHints, QueryEditorMode, QueryEditorModeToggle, QueryEditorRow, QueryFormat, QueryHeaderSwitch, QueryModellerBase, QueryOptionGroup, ROOT_CONFIG_FIELDS, RawQuery, RunQueryButton, RunQueryButtons, SQLEditor, SQLEditorMode, SQLEditorTestUtils, SecureSocksProxyToggle, Segment, Space, SqlDatasource, SqlQueryEditor, StatementPosition, SuggestionKind, TLSSettings, TableSelector, TokenType, buildCelContext, buildCloneDatasourcePayload, buildCreateDatasourcePayload, buildUpdateDatasourcePayload, clearExpressionCache, computeVirtualFieldValues, convertLegacyAuthProps, datasourceToProvisioningYaml, evaluateCelDirect, evaluateCelExpression, evaluateComputedRead, evaluateDependsOn, extractFieldRefs, fetchConfigSchema, formKey, formatDate, formatYamlDiff, generateLLMHint, generateProvisioningTemplate, generateTroubleshootingFields, getConfigSchema, getRequestLooper, getStandardSQLCompletionProvider, getWatchedValue, language as grafanaStandardSQLLanguage, conf as grafanaStandardSQLLanguageConf, isAuthGroupId, isValidCelExpression, parseDependsOn, resolveActiveOverride, resolveGroups, resolveRequiredFieldsGroup, toOption, useDatasourceSchema, useHealthChecks };
|
|
2016
|
+
export type { Aggregate, AllowedValuesValidationRule, Props$c as AuthProps, BaseFieldRef, BaseValidationRule, ColumnDefinition, ComputedMapping, ConfigField, ConfigGroup, CustomMeta, CustomValidationRule, DB, DataLinkConfig, DatasourceConfigSchema, DatasourceConfigWizardProps, DatasourceHealth, DatePickerProps, DatePickerWithInputProps, DebounceInputProps, DirectMapping, Expression, FieldEffect, FieldItemSchema, FieldKind, FieldOption, FieldOverride, FieldPack, FieldPackID, FieldPatch, FieldRelationship, FieldUI, FieldValidationRule, FormState, HealthState, IndexedPairMapping, Instruction, ItemCountValidationRule, LanguageCompletionProvider, LanguageDefinition, LengthValidationRule, MappingField, MetaDefinition, NameValue, PatternValidationRule, PositionContext, Props$s as Props, QueryBuilderLabelFilter, QueryBuilderOperation, QueryBuilderOperationDefinition, QueryBuilderOperationParamDef, QueryBuilderOperationParamEditorProps, QueryBuilderOperationParamValue, QueryEditorProps, QueryRowFilter, QueryStats, QueryWithDefaults, RAQBFieldTypes, RangeValidationRule, RelationshipType, RequestLoopOptions, ResolvedGroup, ResourceSelectorProps, ResponseParser, Role, RunQueryButtonsProps, RunningQueryInfo, SQLConnectionLimits, SQLExpression, SQLFilters, SQLMonarchLanguage, SQLOptions, SQLQuery, SQLSelectableValue, SchemaDefinition, SecureFieldState, SegmentProps, SqlQueryForInterpolation, SqlQueryModel, StatementPlacementProvider, StorageMapping, SuggestionKindProvider, Props$f as TLSSettingsProps, TableDefinition, TableFieldSchema, TableIdentifier, TableSchema, TargetLocation, TestQueryModel, UIComponent, UIWidth, ValidationResults, ValueType, VisualQuery, VisualQueryBinary, VisualQueryModeller };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DataSourceWithBackend, config, getBackendSrv, toDataQueryResponse } from '@grafana/runtime';
|
|
2
|
-
import {
|
|
2
|
+
import { lt } from 'semver';
|
|
3
3
|
import { getRequestLooper } from './requestLooper.js';
|
|
4
4
|
import { of } from '../node_modules/rxjs/dist/esm5/internal/observable/of.js';
|
|
5
5
|
import { merge } from '../node_modules/rxjs/dist/esm5/internal/observable/merge.js';
|
|
@@ -97,7 +97,7 @@ class DatasourceWithAsyncBackend extends DataSourceWithBackend {
|
|
|
97
97
|
};
|
|
98
98
|
const cachingDisabled = !config.featureToggles.awsAsyncQueryCaching;
|
|
99
99
|
if (cachingDisabled && isRunning(status)) {
|
|
100
|
-
const requestSkipQueryCacheUnsupported =
|
|
100
|
+
const requestSkipQueryCacheUnsupported = lt(config.buildInfo.version, "10.2.3");
|
|
101
101
|
if (requestSkipQueryCacheUnsupported) {
|
|
102
102
|
return getBackendSrv().fetch({
|
|
103
103
|
method: "POST",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatasourceWithAsyncBackend.js","sources":["../../../src/async-query-data/DatasourceWithAsyncBackend.ts"],"sourcesContent":["import type {\n DataFrame,\n DataQuery,\n DataQueryRequest,\n DataQueryResponse,\n DataSourceInstanceSettings,\n DataSourceJsonData,\n} from '@grafana/data';\nimport {\n DataSourceWithBackend,\n config,\n getBackendSrv,\n toDataQueryResponse,\n type BackendDataSourceResponse,\n} from '@grafana/runtime';\nimport { merge, of, type Observable } from 'rxjs';\nimport { catchError, map } from 'rxjs/operators';\nimport { lt } from 'semver';\nimport { getRequestLooper } from './requestLooper';\n\nexport interface CustomMeta {\n queryID: string;\n status: string;\n}\n\nexport interface RunningQueryInfo {\n queryID?: string;\n shouldCancel?: boolean;\n}\n\ninterface DataQueryMeta {\n meta?: { queryFlow?: 'async' | 'sync' };\n}\n\nconst RUNNING_STATUSES = ['started', 'submitted', 'running'];\nconst isRunning = (status = '') => RUNNING_STATUSES.includes(status);\nconst isCustomMeta = (meta: unknown): meta is CustomMeta => {\n return !!(typeof meta === 'object' && meta?.hasOwnProperty('queryID') && meta?.hasOwnProperty('status'));\n};\n\nexport class DatasourceWithAsyncBackend<\n TQuery extends DataQuery = DataQuery,\n TOptions extends DataSourceJsonData = DataSourceJsonData,\n> extends DataSourceWithBackend<TQuery, TOptions> {\n private runningQueries: { [hash: string]: RunningQueryInfo } = {};\n private requestCounter = 100;\n private requestIdPrefix: number | string;\n\n constructor(instanceSettings: DataSourceInstanceSettings<TOptions>) {\n super(instanceSettings);\n this.requestIdPrefix = instanceSettings.uid ?? instanceSettings.id;\n }\n\n query(request: DataQueryRequest<TQuery>): Observable<DataQueryResponse> {\n const targets = this.filterQuery ? request.targets.filter(this.filterQuery) : request.targets;\n if (!targets.length) {\n return of({ data: [] });\n }\n const all: Array<Observable<DataQueryResponse>> = [];\n for (let target of targets) {\n if (target.hide) {\n continue;\n }\n all.push(this.doSingle(target, request));\n }\n return merge(...all);\n }\n\n storeQuery(target: TQuery, queryInfo: RunningQueryInfo) {\n const key = JSON.stringify(target);\n const existingQueryInfo = this.runningQueries[key] || {};\n this.runningQueries[key] = { ...existingQueryInfo, ...queryInfo };\n }\n\n getQuery(target: TQuery) {\n const key = JSON.stringify(target);\n return this.runningQueries[key] || {};\n }\n\n removeQuery(target: TQuery) {\n const key = JSON.stringify(target);\n delete this.runningQueries[key];\n }\n\n doSingle(target: TQuery, request: DataQueryRequest<TQuery>): Observable<DataQueryResponse> {\n let queryID: string | undefined = undefined;\n let status: string | undefined = undefined;\n let allData: DataFrame[] = [];\n\n return getRequestLooper(\n { ...request, targets: [target], requestId: `${this.requestIdPrefix}_${this.requestCounter++}` },\n {\n /**\n * Additional query to execute if the current query is still in a running state\n */\n getNextQuery: (rsp: DataQueryResponse) => {\n if (rsp.data?.length) {\n const first: DataFrame = rsp.data[0];\n const meta = first.meta?.custom;\n\n if (isCustomMeta(meta) && isRunning(meta.status)) {\n queryID = meta.queryID;\n status = meta.status;\n this.storeQuery(target, { queryID });\n return { ...target, queryID };\n }\n }\n\n this.removeQuery(target);\n return undefined;\n },\n\n /**\n * The original request\n */\n query: (request: DataQueryRequest<TQuery>) => {\n const { range, targets, requestId, intervalMs, maxDataPoints } = request;\n const [_query] = targets;\n const query: TQuery & DataQueryMeta = {\n ..._query,\n meta: { queryFlow: 'async' },\n intervalMs,\n maxDataPoints,\n // getRef optionally chained to support < v8.3.x of Grafana\n datasource: this?.getRef(),\n datasourceId: this.id,\n ...this.applyTemplateVariables(_query, request.scopedVars),\n };\n\n // Manually bypass the query cache for running queries if the caching service is not enabled.\n // The caching service handles bypassing the query cache automatically when it is enabled.\n const cachingDisabled = !config.featureToggles.awsAsyncQueryCaching;\n if (cachingDisabled && isRunning(status)) {\n const requestSkipQueryCacheUnsupported = lt(config.buildInfo.version, '10.2.3');\n if (requestSkipQueryCacheUnsupported) {\n return getBackendSrv()\n .fetch<BackendDataSourceResponse>({\n method: 'POST',\n url: '/api/ds/query',\n headers: { 'X-Cache-Skip': true },\n requestId,\n data: {\n queries: [query],\n range: range,\n from: range.from.valueOf().toString(),\n to: range.to.valueOf().toString(),\n },\n })\n .pipe(\n map((result) => ({ data: toDataQueryResponse(result).data })),\n catchError((err) => of(toDataQueryResponse(err)))\n );\n }\n\n return super.query({ ...request, targets: [query], skipQueryCache: true });\n }\n\n return super.query({ ...request, targets: [query] });\n },\n\n /**\n * Process the results\n */\n process: (data: DataFrame[]) => {\n for (const frame of data) {\n if (frame.fields.length > 0) {\n allData.push(frame);\n }\n }\n\n return allData;\n },\n\n shouldCancel: () => {\n const { shouldCancel } = this.getQuery(target);\n return !!shouldCancel;\n },\n\n /**\n * Callback that gets executed when unsubscribed\n */\n onCancel: () => {\n if (queryID) {\n this.removeQuery(target);\n this.postResource('cancel', {\n queryId: queryID,\n }).catch((err) => {\n err.isHandled = true; // avoid the popup\n console.error(`error cancelling query ID: ${queryID}`, err);\n });\n }\n },\n }\n );\n }\n\n // cancel sets shouldCancel to tell requestLooper to cancel the query\n cancel = (target: TQuery) => {\n this.storeQuery(target, { shouldCancel: true });\n };\n}\n"],"names":["request","lt"],"mappings":";;;;;;;;;;;AAkCA,MAAM,gBAAA,GAAmB,CAAC,SAAA,EAAW,WAAA,EAAa,SAAS,CAAA;AAC3D,MAAM,YAAY,CAAC,MAAA,GAAS,EAAA,KAAO,gBAAA,CAAiB,SAAS,MAAM,CAAA;AACnE,MAAM,YAAA,GAAe,CAAC,IAAA,KAAsC;AAC1D,EAAA,OAAO,CAAC,EAAE,OAAO,IAAA,KAAS,aAAY,IAAA,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAM,cAAA,CAAe,SAAA,CAAA,CAAA,KAAc,IAAA,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAM,cAAA,CAAe,QAAA,CAAA,CAAA,CAAA;AAChG,CAAA;AAEO,MAAM,mCAGH,qBAAA,CAAwC;AAAA,EAKhD,YAAY,gBAAA,EAAwD;AAhD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,MAAM;AAClB,UAAA,MAAM,EAAE,YAAA,EAAa,GAAI,IAAA,CAAK,SAAS,MAAM,CAAA;AAC7C,UAAA,OAAO,CAAC,CAAC,YAAA;AAAA,QACX,CAAA;AAAA;AAAA;AAAA;AAAA,QAKA,UAAU,MAAM;AACd,UAAA,IAAI,OAAA,EAAS;AACX,YAAA,IAAA,CAAK,YAAY,MAAM,CAAA;AACvB,YAAA,IAAA,CAAK,aAAa,QAAA,EAAU;AAAA,cAC1B,OAAA,EAAS;AAAA,aACV,CAAA,CAAE,KAAA,CAAM,CAAC,GAAA,KAAQ;AAChB,cAAA,GAAA,CAAI,SAAA,GAAY,IAAA;AAChB,cAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,2BAAA,EAA8B,OAAO,CAAA,CAAA,EAAI,GAAG,CAAA;AAAA,YAC5D,CAAC,CAAA;AAAA,UACH;AAAA,QACF;AAAA;AACF,KACF;AAAA,EACF;AAMF;;;;"}
|
|
1
|
+
{"version":3,"file":"DatasourceWithAsyncBackend.js","sources":["../../../src/async-query-data/DatasourceWithAsyncBackend.ts"],"sourcesContent":["import type {\n DataFrame,\n DataQuery,\n DataQueryRequest,\n DataQueryResponse,\n DataSourceInstanceSettings,\n DataSourceJsonData,\n} from '@grafana/data';\nimport {\n DataSourceWithBackend,\n config,\n getBackendSrv,\n toDataQueryResponse,\n type BackendDataSourceResponse,\n} from '@grafana/runtime';\nimport { merge, of, type Observable } from 'rxjs';\nimport { catchError, map } from 'rxjs/operators';\nimport { lt } from 'semver';\nimport { getRequestLooper } from './requestLooper';\n\nexport interface CustomMeta {\n queryID: string;\n status: string;\n}\n\nexport interface RunningQueryInfo {\n queryID?: string;\n shouldCancel?: boolean;\n}\n\ninterface DataQueryMeta {\n meta?: { queryFlow?: 'async' | 'sync' };\n}\n\nconst RUNNING_STATUSES = ['started', 'submitted', 'running'];\nconst isRunning = (status = '') => RUNNING_STATUSES.includes(status);\nconst isCustomMeta = (meta: unknown): meta is CustomMeta => {\n return !!(typeof meta === 'object' && meta?.hasOwnProperty('queryID') && meta?.hasOwnProperty('status'));\n};\n\nexport class DatasourceWithAsyncBackend<\n TQuery extends DataQuery = DataQuery,\n TOptions extends DataSourceJsonData = DataSourceJsonData,\n> extends DataSourceWithBackend<TQuery, TOptions> {\n private runningQueries: { [hash: string]: RunningQueryInfo } = {};\n private requestCounter = 100;\n private requestIdPrefix: number | string;\n\n constructor(instanceSettings: DataSourceInstanceSettings<TOptions>) {\n super(instanceSettings);\n this.requestIdPrefix = instanceSettings.uid ?? instanceSettings.id;\n }\n\n query(request: DataQueryRequest<TQuery>): Observable<DataQueryResponse> {\n const targets = this.filterQuery ? request.targets.filter(this.filterQuery) : request.targets;\n if (!targets.length) {\n return of({ data: [] });\n }\n const all: Array<Observable<DataQueryResponse>> = [];\n for (let target of targets) {\n if (target.hide) {\n continue;\n }\n all.push(this.doSingle(target, request));\n }\n return merge(...all);\n }\n\n storeQuery(target: TQuery, queryInfo: RunningQueryInfo) {\n const key = JSON.stringify(target);\n const existingQueryInfo = this.runningQueries[key] || {};\n this.runningQueries[key] = { ...existingQueryInfo, ...queryInfo };\n }\n\n getQuery(target: TQuery) {\n const key = JSON.stringify(target);\n return this.runningQueries[key] || {};\n }\n\n removeQuery(target: TQuery) {\n const key = JSON.stringify(target);\n delete this.runningQueries[key];\n }\n\n doSingle(target: TQuery, request: DataQueryRequest<TQuery>): Observable<DataQueryResponse> {\n let queryID: string | undefined = undefined;\n let status: string | undefined = undefined;\n let allData: DataFrame[] = [];\n\n return getRequestLooper(\n { ...request, targets: [target], requestId: `${this.requestIdPrefix}_${this.requestCounter++}` },\n {\n /**\n * Additional query to execute if the current query is still in a running state\n */\n getNextQuery: (rsp: DataQueryResponse) => {\n if (rsp.data?.length) {\n const first: DataFrame = rsp.data[0];\n const meta = first.meta?.custom;\n\n if (isCustomMeta(meta) && isRunning(meta.status)) {\n queryID = meta.queryID;\n status = meta.status;\n this.storeQuery(target, { queryID });\n return { ...target, queryID };\n }\n }\n\n this.removeQuery(target);\n return undefined;\n },\n\n /**\n * The original request\n */\n query: (request: DataQueryRequest<TQuery>) => {\n const { range, targets, requestId, intervalMs, maxDataPoints } = request;\n const [_query] = targets;\n const query: TQuery & DataQueryMeta = {\n ..._query,\n meta: { queryFlow: 'async' },\n intervalMs,\n maxDataPoints,\n // getRef optionally chained to support < v8.3.x of Grafana\n datasource: this?.getRef(),\n datasourceId: this.id,\n ...this.applyTemplateVariables(_query, request.scopedVars),\n };\n\n // Manually bypass the query cache for running queries if the caching service is not enabled.\n // The caching service handles bypassing the query cache automatically when it is enabled.\n const cachingDisabled = !config.featureToggles.awsAsyncQueryCaching;\n if (cachingDisabled && isRunning(status)) {\n const requestSkipQueryCacheUnsupported = lt(config.buildInfo.version, '10.2.3');\n if (requestSkipQueryCacheUnsupported) {\n return getBackendSrv()\n .fetch<BackendDataSourceResponse>({\n method: 'POST',\n url: '/api/ds/query',\n headers: { 'X-Cache-Skip': true },\n requestId,\n data: {\n queries: [query],\n range: range,\n from: range.from.valueOf().toString(),\n to: range.to.valueOf().toString(),\n },\n })\n .pipe(\n map((result) => ({ data: toDataQueryResponse(result).data })),\n catchError((err) => of(toDataQueryResponse(err)))\n );\n }\n\n return super.query({ ...request, targets: [query], skipQueryCache: true });\n }\n\n return super.query({ ...request, targets: [query] });\n },\n\n /**\n * Process the results\n */\n process: (data: DataFrame[]) => {\n for (const frame of data) {\n if (frame.fields.length > 0) {\n allData.push(frame);\n }\n }\n\n return allData;\n },\n\n shouldCancel: () => {\n const { shouldCancel } = this.getQuery(target);\n return !!shouldCancel;\n },\n\n /**\n * Callback that gets executed when unsubscribed\n */\n onCancel: () => {\n if (queryID) {\n this.removeQuery(target);\n this.postResource('cancel', {\n queryId: queryID,\n }).catch((err) => {\n err.isHandled = true; // avoid the popup\n console.error(`error cancelling query ID: ${queryID}`, err);\n });\n }\n },\n }\n );\n }\n\n // cancel sets shouldCancel to tell requestLooper to cancel the query\n cancel = (target: TQuery) => {\n this.storeQu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} from '@grafana/ui';
|
|
3
3
|
import '@grafana/data';
|
|
4
4
|
import { selectors } from '@grafana/e2e-selectors';
|
|
5
|
+
import { useDataSourceInstanceList, useDataSourceInstanceListItem } from '@grafana/plugin-compat/datasources';
|
|
5
6
|
import { isUnsignedPluginSignature, PluginSignatureBadge } from '../Plugins/PluginSignatureBadge.js';
|
|
6
|
-
import { getDataSourceSrv } from '@grafana/runtime';
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
8
|
+
function DataSourcePicker({
|
|
9
|
+
onChange,
|
|
10
|
+
current: currentProp,
|
|
11
|
+
hideTextValue,
|
|
12
|
+
onBlur,
|
|
13
|
+
autoFocus = false,
|
|
14
|
+
openMenuOnFocus = false,
|
|
15
|
+
placeholder = "Select datasource",
|
|
16
|
+
noDefault
|
|
17
|
+
}) {
|
|
18
|
+
const current = currentProp != null ? currentProp : null;
|
|
19
|
+
const showNoDatasources = !current && !!noDefault;
|
|
20
|
+
const { items, isLoading: isListLoading, error: listError } = useDataSourceInstanceList();
|
|
21
|
+
const currentResult = useDataSourceInstanceListItem(current);
|
|
22
|
+
const selected = currentResult.item;
|
|
23
|
+
const isCurrentLoading = !showNoDatasources && currentResult.isLoading;
|
|
24
|
+
const isLoading = isListLoading || isCurrentLoading;
|
|
25
|
+
const notFound = !selected && !isCurrentLoading && !showNoDatasources;
|
|
26
|
+
const handleChange = (option) => {
|
|
27
|
+
const item = items.find((ds) => ds.uid === option.value);
|
|
28
|
+
if (item) {
|
|
29
|
+
onChange(item);
|
|
29
30
|
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
31
|
+
};
|
|
32
|
+
const options = items.map((ds) => ({
|
|
33
|
+
value: ds.uid,
|
|
34
|
+
label: ds.name,
|
|
35
|
+
imgUrl: ds.meta.info.logos.small,
|
|
36
|
+
meta: ds.meta
|
|
37
|
+
}));
|
|
38
|
+
const value = getCurrentValue({ current, selected, notFound, showNoDatasources, hideTextValue });
|
|
39
|
+
const invalid = !!listError || notFound;
|
|
40
|
+
return /* @__PURE__ */ React.createElement("div", { "aria-label": selectors.components.DataSourcePicker.container }, /* @__PURE__ */ React.createElement(
|
|
41
|
+
Select,
|
|
42
|
+
{
|
|
43
|
+
className: "ds-picker select-container",
|
|
44
|
+
isMulti: false,
|
|
45
|
+
isClearable: false,
|
|
46
|
+
backspaceRemovesValue: false,
|
|
47
|
+
onChange: handleChange,
|
|
48
|
+
options,
|
|
49
|
+
isLoading,
|
|
50
|
+
autoFocus,
|
|
51
|
+
onBlur,
|
|
52
|
+
openMenuOnFocus,
|
|
53
|
+
maxMenuHeight: 500,
|
|
54
|
+
placeholder,
|
|
55
|
+
noOptionsMessage: listError ? "Could not load data sources" : "No datasources found",
|
|
56
|
+
value,
|
|
57
|
+
invalid,
|
|
58
|
+
"aria-invalid": invalid,
|
|
59
|
+
getOptionLabel: (o) => {
|
|
60
|
+
if (o.meta && isUnsignedPluginSignature(o.meta.signature) && o !== value) {
|
|
61
|
+
return /* @__PURE__ */ React.createElement(Stack, { alignItems: "center", justifyContent: "space-between" }, /* @__PURE__ */ React.createElement("span", null, o.label), " ", /* @__PURE__ */ React.createElement(PluginSignatureBadge, { status: o.meta.signature }));
|
|
62
|
+
}
|
|
63
|
+
return o.label || "";
|
|
64
|
+
}
|
|
47
65
|
}
|
|
66
|
+
));
|
|
67
|
+
}
|
|
68
|
+
function getCurrentValue({
|
|
69
|
+
current,
|
|
70
|
+
selected,
|
|
71
|
+
notFound,
|
|
72
|
+
showNoDatasources,
|
|
73
|
+
hideTextValue
|
|
74
|
+
}) {
|
|
75
|
+
if (showNoDatasources) {
|
|
48
76
|
return {
|
|
49
|
-
label:
|
|
50
|
-
value: (current != null ? current : "no name") + " - not found",
|
|
51
|
-
imgUrl: "",
|
|
52
|
-
hideText: hideTextValue
|
|
77
|
+
label: "No datasources found"
|
|
53
78
|
};
|
|
54
79
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
value: ds.uid,
|
|
58
|
-
label: ds.name,
|
|
59
|
-
imgUrl: ds.meta.info.logos.small,
|
|
60
|
-
meta: ds.meta
|
|
61
|
-
}));
|
|
62
|
-
return options;
|
|
80
|
+
if (selected) {
|
|
81
|
+
return toOption$1(selected, hideTextValue);
|
|
63
82
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const { error } = this.state;
|
|
67
|
-
const options = this.getDataSourceOptions();
|
|
68
|
-
const value = this.getCurrentValue();
|
|
69
|
-
return /* @__PURE__ */ React.createElement("div", { "aria-label": selectors.components.DataSourcePicker.container }, /* @__PURE__ */ React.createElement(
|
|
70
|
-
Select,
|
|
71
|
-
{
|
|
72
|
-
className: "ds-picker select-container",
|
|
73
|
-
isMulti: false,
|
|
74
|
-
isClearable: false,
|
|
75
|
-
backspaceRemovesValue: false,
|
|
76
|
-
onChange: this.onChange,
|
|
77
|
-
options,
|
|
78
|
-
autoFocus,
|
|
79
|
-
onBlur,
|
|
80
|
-
openMenuOnFocus,
|
|
81
|
-
maxMenuHeight: 500,
|
|
82
|
-
placeholder,
|
|
83
|
-
noOptionsMessage: "No datasources found",
|
|
84
|
-
value,
|
|
85
|
-
invalid: !!error,
|
|
86
|
-
getOptionLabel: (o) => {
|
|
87
|
-
if (o.meta && isUnsignedPluginSignature(o.meta.signature) && o !== value) {
|
|
88
|
-
return /* @__PURE__ */ React.createElement(Stack, { alignItems: "center", justifyContent: "space-between" }, /* @__PURE__ */ React.createElement("span", null, o.label), " ", /* @__PURE__ */ React.createElement(PluginSignatureBadge, { status: o.meta.signature }));
|
|
89
|
-
}
|
|
90
|
-
return o.label || "";
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
));
|
|
83
|
+
if (!notFound) {
|
|
84
|
+
return void 0;
|
|
94
85
|
}
|
|
86
|
+
return {
|
|
87
|
+
label: (current != null ? current : "no name") + " - not found",
|
|
88
|
+
value: (current != null ? current : "no name") + " - not found",
|
|
89
|
+
imgUrl: "",
|
|
90
|
+
hideText: hideTextValue
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function toOption$1(ds, hideTextValue) {
|
|
94
|
+
return {
|
|
95
|
+
label: ds.name.substr(0, 37),
|
|
96
|
+
value: ds.name,
|
|
97
|
+
imgUrl: ds.meta.info.logos.small,
|
|
98
|
+
hideText: hideTextValue,
|
|
99
|
+
meta: ds.meta
|
|
100
|
+
};
|
|
95
101
|
}
|
|
96
|
-
__publicField$6(DataSourcePicker, "defaultProps", {
|
|
97
|
-
autoFocus: false,
|
|
98
|
-
openMenuOnFocus: false,
|
|
99
|
-
placeholder: "Select datasource"
|
|
100
|
-
});
|
|
101
102
|
|
|
102
103
|
export { DataSourcePicker };
|
|
103
104
|
//# sourceMappingURL=DataSourcePicker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataSourcePicker.js","sources":["../../../../src/components/DataSourcePicker/DataSourcePicker.tsx"],"sourcesContent":["import React
|
|
1
|
+
{"version":3,"file":"DataSourcePicker.js","sources":["../../../../src/components/DataSourcePicker/DataSourcePicker.tsx"],"sourcesContent":["import React from 'react';\nimport { Stack, Select } from '@grafana/ui';\nimport { type DataSourceInstanceSettings, type SelectableValue } from '@grafana/data';\nimport { selectors } from '@grafana/e2e-selectors';\nimport { useDataSourceInstanceList, useDataSourceInstanceListItem } from '@grafana/plugin-compat/datasources';\nimport { isUnsignedPluginSignature, PluginSignatureBadge } from '../Plugins/PluginSignatureBadge';\n\nexport interface Props {\n // Mirrors `DataSourceInstanceListItem` instead of importing it: `@grafana/data` only exports it from 13.3,\n // so with our `^13.0.0` peer range consumers on 13.0–13.2 would get `any`. Callbacks typed with the real\n // `DataSourceInstanceListItem` (13.3+) still fit because the shapes are identical.\n /**\n * Receives the selected data source's list item (`uid`, `type`, `name`, `meta`). Call\n * `getDataSourceInstanceSettings(ds.uid)` from `@grafana/plugin-compat` if you need the full settings.\n */\n onChange: (ds: Pick<DataSourceInstanceSettings, 'uid' | 'type' | 'name' | 'meta'>) => void;\n /**\n * Reference to the selected data source, resolved the way Grafana does: uid, name, template variable or\n * built-in. `null`/`undefined` resolves to the default data source.\n */\n current?: string | null;\n hideTextValue?: boolean;\n onBlur?: () => void;\n autoFocus?: boolean;\n openMenuOnFocus?: boolean;\n placeholder?: string;\n tracing?: boolean;\n mixed?: boolean;\n dashboard?: boolean;\n metrics?: boolean;\n annotations?: boolean;\n variables?: boolean;\n pluginId?: string;\n noDefault?: boolean;\n}\n\ntype DataSourceListItem = Parameters<Props['onChange']>[0];\n\nexport function DataSourcePicker({\n onChange,\n current: currentProp,\n hideTextValue,\n onBlur,\n autoFocus = false,\n openMenuOnFocus = false,\n placeholder = 'Select datasource',\n noDefault,\n}: Props) {\n const current = currentProp ?? null;\n const showNoDatasources = !current && !!noDefault;\n const { items, isLoading: isListLoading, error: listError } = useDataSourceInstanceList();\n const currentResult = useDataSourceInstanceListItem(current);\n const selected: DataSourceListItem | undefined = currentResult.item;\n const isCurrentLoading = !showNoDatasources && currentResult.isLoading;\n const isLoading = isListLoading || isCurrentLoading;\n const notFound = !selected && !isCurrentLoading && !showNoDatasources;\n\n const handleChange = (option: SelectableValue<string>) => {\n const item = items.find((ds) => ds.uid === option.value);\n if (item) {\n onChange(item);\n }\n };\n\n const options: Array<SelectableValue<string>> = items.map((ds) => ({\n value: ds.uid,\n label: ds.name,\n imgUrl: ds.meta.info.logos.small,\n meta: ds.meta,\n }));\n\n const value = getCurrentValue({ current, selected, notFound, showNoDatasources, hideTextValue });\n const invalid = !!listError || notFound;\n\n return (\n <div aria-label={selectors.components.DataSourcePicker.container}>\n <Select\n className=\"ds-picker select-container\"\n isMulti={false}\n isClearable={false}\n backspaceRemovesValue={false}\n onChange={handleChange}\n options={options}\n isLoading={isLoading}\n autoFocus={autoFocus}\n onBlur={onBlur}\n openMenuOnFocus={openMenuOnFocus}\n maxMenuHeight={500}\n placeholder={placeholder}\n noOptionsMessage={listError ? 'Could not load data sources' : 'No datasources found'}\n value={value}\n invalid={invalid}\n aria-invalid={invalid}\n getOptionLabel={(o) => {\n if (o.meta && isUnsignedPluginSignature(o.meta.signature) && o !== value) {\n return (\n <Stack alignItems=\"center\" justifyContent=\"space-between\">\n <span>{o.label}</span> <PluginSignatureBadge status={o.meta.signature} />\n </Stack>\n );\n }\n return o.label || '';\n }}\n />\n </div>\n );\n}\n\nfunction getCurrentValue({\n current,\n selected,\n notFound,\n showNoDatasources,\n hideTextValue,\n}: {\n current: string | null;\n selected?: DataSourceListItem;\n notFound: boolean;\n showNoDatasources: boolean;\n hideTextValue?: boolean;\n}): SelectableValue<string> | undefined {\n if (showNoDatasources) {\n return {\n label: 'No datasources found',\n };\n }\n\n if (selected) {\n return toOption(selected, hideTextValue);\n }\n\n if (!notFound) {\n return undefined;\n }\n\n return {\n label: (current ?? 'no name') + ' - not found',\n value: (current ?? 'no name') + ' - not found',\n imgUrl: '',\n hideText: hideTextValue,\n };\n}\n\nfunction toOption(ds: DataSourceListItem, hideTextValue?: boolean): SelectableValue<string> {\n return {\n label: ds.name.substr(0, 37),\n value: ds.name,\n imgUrl: ds.meta.info.logos.small,\n hideText: hideTextValue,\n meta: ds.meta,\n };\n}\n"],"names":["toOption"],"mappings":";;;;;;;AAsCO,SAAS,gBAAA,CAAiB;AAAA,EAC/B,QAAA;AAAA,EACA,OAAA,EAAS,WAAA;AAAA,EACT,aAAA;AAAA,EACA,MAAA;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AACF,CAAA,EAMwC;AACtC,EAAA,IAAI,iBAAA,EAAmB;AACrB,IAAA,OAAO;AAAA,MACL,KAAA,EAAO;AAAA,KACT;AAAA,EACF;AAEA,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,OAAOA,UAAA,CAAS,UAAU,aAAa,CAAA;AAAA,EACzC;AAEA,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO;AAAA,IACL,KAAA,EAAA,CAAQ,4BAAW,SAAA,IAAa,cAAA;AAAA,IAChC,KAAA,EAAA,CAAQ,4BAAW,SAAA,IAAa,cAAA;AAAA,IAChC,MAAA,EAAQ,EAAA;AAAA,IACR,QAAA,EAAU;AAAA,GACZ;AACF;AAEA,SAASA,UAAA,CAAS,IAAwB,aAAA,EAAkD;AAC1F,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,EAAA,CAAG,IAAA,CAAK,MAAA,CAAO,GAAG,EAAE,CAAA;AAAA,IAC3B,OAAO,EAAA,CAAG,IAAA;AAAA,IACV,MAAA,EAAQ,EAAA,CAAG,IAAA,CAAK,IAAA,CAAK,KAAA,CAAM,KAAA;AAAA,IAC3B,QAAA,EAAU,aAAA;AAAA,IACV,MAAM,EAAA,CAAG;AAAA,GACX;AACF;;;;"}
|
|
@@ -27,7 +27,7 @@ class SqlDatasource extends DataSourceWithBackend {
|
|
|
27
27
|
const result = this.getQueryModel().quoteLiteral(value);
|
|
28
28
|
return result;
|
|
29
29
|
} else {
|
|
30
|
-
return value;
|
|
30
|
+
return value.replace(/'/g, "''");
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
if (typeof value === "number") {
|
|
@@ -65,14 +65,16 @@ class SqlDatasource extends DataSourceWithBackend {
|
|
|
65
65
|
}
|
|
66
66
|
applyTemplateVariables(target, scopedVars) {
|
|
67
67
|
const queryModel = this.getQueryModel(target, this.templateSrv, scopedVars);
|
|
68
|
-
const rawSql = this.clean(queryModel.interpolate());
|
|
69
68
|
return {
|
|
70
69
|
refId: target.refId,
|
|
71
70
|
datasource: this.getRef(),
|
|
72
|
-
rawSql,
|
|
71
|
+
rawSql: queryModel.interpolate(),
|
|
73
72
|
format: target.format
|
|
74
73
|
};
|
|
75
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* @deprecated `applyTemplateVariables` no longer calls this. Collapsing `''` to `'` breaks valid SQL string literals.
|
|
77
|
+
*/
|
|
76
78
|
clean(value) {
|
|
77
79
|
return value.replace(/''/g, "'");
|
|
78
80
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SqlDatasource.js","sources":["../../../src/datasource/SqlDatasource.ts"],"sourcesContent":["import { lastValueFrom, of } from 'rxjs';\nimport { catchError, map } from 'rxjs/operators';\n\nimport {\n type DataFrame,\n DataFrameView,\n type DataSourceInstanceSettings,\n type MetricFindValue,\n type ScopedVars,\n type TimeRange,\n type VariableModel,\n} from '@grafana/data';\nimport {\n type BackendDataSourceResponse,\n DataSourceWithBackend,\n type FetchResponse,\n getBackendSrv,\n getTemplateSrv,\n type TemplateSrv,\n toDataQueryResponse,\n} from '@grafana/runtime';\nimport { type DataQuery } from '@grafana/schema';\n\nimport { MACRO_NAMES } from './constants';\n// import { toTestingStatus } from '@grafana/runtime/utils/queryResponse';\nimport {\n type DB,\n QueryFormat,\n type ResponseParser,\n type SQLOptions,\n type SQLQuery,\n type SqlQueryModel,\n} from '../components/QueryEditor/types';\n\nexport interface SearchFilterOptions {\n searchFilter?: string;\n}\n\nexport interface VariableWithMultiSupport extends VariableWithOptions {\n multi: boolean;\n includeAll: boolean;\n allValue?: string | null;\n}\n\nexport interface VariableWithOptions extends VariableModel {\n current: VariableOption;\n options: VariableOption[];\n query: string;\n}\n\nexport interface VariableOption {\n selected: boolean;\n text: string | string[];\n value: string | string[];\n isNone?: boolean;\n}\n\nexport abstract class SqlDatasource extends DataSourceWithBackend<SQLQuery, SQLOptions> {\n id: number;\n name: string;\n interval: string;\n db: DB;\n dataset?: string;\n annotations = {};\n\n constructor(\n instanceSettings: DataSourceInstanceSettings<SQLOptions>,\n protected readonly templateSrv: TemplateSrv = getTemplateSrv()\n ) {\n super(instanceSettings);\n this.name = instanceSettings.name;\n // If the id is not present, set it to 0 - it's deprecated in Grafana 13\n this.id = instanceSettings.id ?? 0;\n const settingsData = instanceSettings.jsonData || {};\n this.interval = settingsData.timeInterval || '1m';\n this.db = this.getDB();\n }\n\n abstract getDB(dsID?: number): DB;\n\n abstract getQueryModel(target?: SQLQuery, templateSrv?: TemplateSrv, scopedVars?: ScopedVars): SqlQueryModel;\n\n abstract getResponseParser(): ResponseParser;\n\n interpolateVariable = (value: string | string[] | number, variable: VariableWithMultiSupport) => {\n if (typeof value === 'string') {\n if (variable.multi || variable.includeAll) {\n const result = this.getQueryModel().quoteLiteral(value);\n return result;\n } else {\n return value;\n }\n }\n\n if (typeof value === 'number') {\n return value;\n }\n\n if (Array.isArray(value)) {\n const quotedValues = value.map((v) => this.getQueryModel().quoteLiteral(v));\n return quotedValues.join(',');\n }\n\n return value;\n };\n\n interpolateVariablesInQueries(queries: SQLQuery[], scopedVars: ScopedVars): SQLQuery[] {\n let expandedQueries = queries;\n if (queries && queries.length > 0) {\n expandedQueries = queries.map((query) => {\n const expandedQuery = {\n ...query,\n datasource: this.getRef(),\n rawSql: this.templateSrv.replace(query.rawSql, scopedVars, this.interpolateVariable),\n rawQuery: true,\n };\n return expandedQuery;\n });\n }\n return expandedQueries;\n }\n\n filterQuery(query: SQLQuery): boolean {\n return !query.hide;\n }\n\n applyTemplateVariables(target: SQLQuery, scopedVars: ScopedVars): SQLQuery {\n const queryModel = this.getQueryModel(target, this.templateSrv, scopedVars);\n const rawSql = this.clean(queryModel.interpolate());\n return {\n refId: target.refId,\n datasource: this.getRef(),\n rawSql,\n format: target.format,\n };\n }\n\n clean(value: string) {\n return value.replace(/''/g, \"'\");\n }\n\n async metricFindQuery(query: string, optionalOptions?: MetricFindQueryOptions): Promise<MetricFindValue[]> {\n const rawSql = this.templateSrv.replace(\n query,\n getSearchFilterScopedVar({ query, wildcardChar: '%', options: optionalOptions }),\n this.interpolateVariable\n );\n\n const interpolatedQuery: SQLQuery = {\n refId: 'tempvar',\n datasource: this.getRef(),\n rawSql,\n format: QueryFormat.Table,\n };\n\n const response = await this.runMetaQuery(interpolatedQuery, optionalOptions);\n return this.getResponseParser().transformMetricFindResponse(response);\n }\n\n async runSql<T extends object>(query: string, options?: RunSQLOptions) {\n const frame = await this.runMetaQuery({ rawSql: query, format: QueryFormat.Table, refId: options?.refId }, options);\n return new DataFrameView<T>(frame);\n }\n\n private runMetaQuery(request: Partial<SQLQuery>, options?: MetricFindQueryOptions): Promise<DataFrame> {\n const refId = request.refId || 'meta';\n const queries: DataQuery[] = [{ ...request, datasource: request.datasource || this.getRef(), refId }];\n\n return lastValueFrom(\n getBackendSrv()\n .fetch<BackendDataSourceResponse>({\n url: '/api/ds/query',\n method: 'POST',\n data: {\n from: options?.range?.from.valueOf().toString(),\n to: options?.range?.to.valueOf().toString(),\n queries,\n },\n requestId: refId,\n })\n .pipe(\n map((res: FetchResponse<BackendDataSourceResponse>) => {\n const rsp = toDataQueryResponse(res, queries);\n return rsp.data[0];\n })\n )\n );\n }\n\n testDatasource(): Promise<{ status: string; message: string }> {\n return lastValueFrom(\n getBackendSrv()\n .fetch({\n url: '/api/ds/query',\n method: 'POST',\n data: {\n from: '5m',\n to: 'now',\n queries: [\n {\n refId: 'A',\n intervalMs: 1,\n maxDataPoints: 1,\n datasource: this.getRef(),\n datasourceId: this.id,\n rawSql: 'SELECT 1',\n format: 'table',\n },\n ],\n },\n })\n .pipe(\n map(() => ({ status: 'success', message: 'Database Connection OK' })),\n catchError((err) => {\n // return of(toTestingStatus(err));\n return of(err);\n })\n )\n );\n }\n\n targetContainsTemplate(target: SQLQuery) {\n let queryWithoutMacros = target.rawSql;\n MACRO_NAMES.forEach((value) => {\n queryWithoutMacros = queryWithoutMacros?.replace(value, '') || '';\n });\n return this.templateSrv.containsTemplate(queryWithoutMacros);\n }\n}\n\ninterface RunSQLOptions extends MetricFindQueryOptions {\n refId?: string;\n}\n\ninterface MetricFindQueryOptions extends SearchFilterOptions {\n range?: TimeRange;\n}\n\nexport const SEARCH_FILTER_VARIABLE = '__searchFilter';\n\nexport const containsSearchFilter = (query: string | unknown): boolean =>\n query && typeof query === 'string' ? query.indexOf(SEARCH_FILTER_VARIABLE) !== -1 : false;\n\nexport const getSearchFilterScopedVar = (args: {\n query: string;\n wildcardChar: string;\n options?: SearchFilterOptions;\n}): ScopedVars => {\n const { query, wildcardChar } = args;\n if (!containsSearchFilter(query)) {\n return {};\n }\n\n let { options } = args;\n\n options = options || { searchFilter: '' };\n const value = options.searchFilter ? `${options.searchFilter}${wildcardChar}` : `${wildcardChar}`;\n\n return {\n __searchFilter: {\n value,\n text: '',\n },\n };\n};\n"],"names":["__publicField"],"mappings":";;;;;;;;;;;;AAyDO,MAAe,sBAAsB,qBAAA,CAA4C;AAAA,EAQtF,WAAA,CACE,gBAAA,EACmB,WAAA,GAA2B,cAAA,EAAe,EAC7D;AApEJ,IAAA,IAAA,EAAA;AAqEI,IAAA,KAAA,CAAM,gBAAgB,CAAA;AAFH,IAAAA,eAAA,CAAA,IAAA,EAAA,aAAA,EAAA,WAAA,CAAA;AATrB,IAAAA,eAAA,CAAA,IAAA,EAAA,IAAA,CAAA;AACA,IAAAA,eAAA,CAAA,IAAA,EAAA,MAAA,CAAA;AACA,IAAAA,eAAA,CAAA,IAAA,EAAA,UAAA,CAAA;AACA,IAAAA,eAAA,CAAA,IAAA,EAAA,IAAA,CAAA;AACA,IAAAA,eAAA,CAAA,IAAA,EAAA,SAAA,CAAA;AACA,IAAAA,eAAA,CAAA,IAAA,EAAA,aAAA,EAAc,EAAC,CAAA;AAqBf,IAAAA,eAAA,CAAA,IAAA,EAAA,qBAAA,EAAsB,CAAC,OAAmC,QAAA,KAAuC;AAC/F,MAAA,IAAI,OAAO,UAAU,QAAA,EAAU;A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AU;AAC7B,MAAA,kBAAA,GAAA,CAAqB,kBAAA,IAAA,IAAA,GAAA,MAAA,GAAA,kBAAA,CAAoB,OAAA,CAAQ,KAAA,EAAO,EAAA,CAAA,KAAO,EAAA;AAAA,IACjE,CAAC,CAAA;AACD,IAAA,OAAO,IAAA,CAAK,WAAA,CAAY,gBAAA,CAAiB,kBAAkB,CAAA;AAAA,EAC7D;AACF;AAUO,MAAM,sBAAA,GAAyB;AAE/B,MAAM,oBAAA,GAAuB,CAAC,KAAA,KACnC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,CAAM,OAAA,CAAQ,sBAAsB,CAAA,KAAM,EAAA,GAAK;AAE/E,MAAM,wBAAA,GAA2B,CAAC,IAAA,KAIvB;AAChB,EAAA,MAAM,EAAE,KAAA,EAAO,YAAA,EAAa,GAAI,IAAA;AAChC,EAAA,IAAI,CAAC,oBAAA,CAAqB,KAAK,CAAA,EAAG;AAChC,IAAA,OAAO,EAAC;AAAA,EACV;AAEA,EAAA,IAAI,EAAE,SAAQ,GAAI,IAAA;AAElB,EAAA,OAAA,GAAU,OAAA,IAAW,EAAE,YAAA,EAAc,EAAA,EAAG;AACxC,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,YAAA,GAAe,CAAA,EAAG,OAAA,CAAQ,YAAY,CAAA,EAAG,YAAY,CAAA,CAAA,GAAK,CAAA,EAAG,YAAY,CAAA,CAAA;AAE/F,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB;AAAA,MACd,KAAA;AAAA,MACA,IAAA,EAAM;AAAA;AACR,GACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"SqlDatasource.js","sources":["../../../src/datasource/SqlDatasource.ts"],"sourcesContent":["import { lastValueFrom, of } from 'rxjs';\nimport { catchError, map } from 'rxjs/operators';\n\nimport {\n type DataFrame,\n DataFrameView,\n type DataSourceInstanceSettings,\n type MetricFindValue,\n type ScopedVars,\n type TimeRange,\n type VariableModel,\n} from '@grafana/data';\nimport {\n type BackendDataSourceResponse,\n DataSourceWithBackend,\n type FetchResponse,\n getBackendSrv,\n getTemplateSrv,\n type TemplateSrv,\n toDataQueryResponse,\n} from '@grafana/runtime';\nimport { type DataQuery } from '@grafana/schema';\n\nimport { MACRO_NAMES } from './constants';\n// import { toTestingStatus } from '@grafana/runtime/utils/queryResponse';\nimport {\n type DB,\n QueryFormat,\n type ResponseParser,\n type SQLOptions,\n type SQLQuery,\n type SqlQueryModel,\n} from '../components/QueryEditor/types';\n\nexport interface SearchFilterOptions {\n searchFilter?: string;\n}\n\nexport interface VariableWithMultiSupport extends VariableWithOptions {\n multi: boolean;\n includeAll: boolean;\n allValue?: string | null;\n}\n\nexport interface VariableWithOptions extends VariableModel {\n current: VariableOption;\n options: VariableOption[];\n query: string;\n}\n\nexport interface VariableOption {\n selected: boolean;\n text: string | string[];\n value: string | string[];\n isNone?: boolean;\n}\n\nexport abstract class SqlDatasource extends DataSourceWithBackend<SQLQuery, SQLOptions> {\n id: number;\n name: string;\n interval: string;\n db: DB;\n dataset?: string;\n annotations = {};\n\n constructor(\n instanceSettings: DataSourceInstanceSettings<SQLOptions>,\n protected readonly templateSrv: TemplateSrv = getTemplateSrv()\n ) {\n super(instanceSettings);\n this.name = instanceSettings.name;\n // If the id is not present, set it to 0 - it's deprecated in Grafana 13\n this.id = instanceSettings.id ?? 0;\n const settingsData = instanceSettings.jsonData || {};\n this.interval = settingsData.timeInterval || '1m';\n this.db = this.getDB();\n }\n\n abstract getDB(dsID?: number): DB;\n\n abstract getQueryModel(target?: SQLQuery, templateSrv?: TemplateSrv, scopedVars?: ScopedVars): SqlQueryModel;\n\n abstract getResponseParser(): ResponseParser;\n\n interpolateVariable = (value: string | string[] | number, variable: VariableWithMultiSupport) => {\n if (typeof value === 'string') {\n if (variable.multi || variable.includeAll) {\n const result = this.getQueryModel().quoteLiteral(value);\n return result;\n } else {\n return value.replace(/'/g, \"''\");\n }\n }\n\n if (typeof value === 'number') {\n return value;\n }\n\n if (Array.isArray(value)) {\n const quotedValues = value.map((v) => this.getQueryModel().quoteLiteral(v));\n return quotedValues.join(',');\n }\n\n return value;\n };\n\n interpolateVariablesInQueries(queries: SQLQuery[], scopedVars: ScopedVars): SQLQuery[] {\n let expandedQueries = queries;\n if (queries && queries.length > 0) {\n expandedQueries = queries.map((query) => {\n const expandedQuery = {\n ...query,\n datasource: this.getRef(),\n rawSql: this.templateSrv.replace(query.rawSql, scopedVars, this.interpolateVariable),\n rawQuery: true,\n };\n return expandedQuery;\n });\n }\n return expandedQueries;\n }\n\n filterQuery(query: SQLQuery): boolean {\n return !query.hide;\n }\n\n applyTemplateVariables(target: SQLQuery, scopedVars: ScopedVars): SQLQuery {\n const queryModel = this.getQueryModel(target, this.templateSrv, scopedVars);\n return {\n refId: target.refId,\n datasource: this.getRef(),\n rawSql: queryModel.interpolate(),\n format: target.format,\n };\n }\n\n /**\n * @deprecated `applyTemplateVariables` no longer calls this. Collapsing `''` to `'` breaks valid SQL string literals.\n */\n clean(value: string) {\n return value.replace(/''/g, \"'\");\n }\n\n async metricFindQuery(query: string, optionalOptions?: MetricFindQueryOptions): Promise<MetricFindValue[]> {\n const rawSql = this.templateSrv.replace(\n query,\n getSearchFilterScopedVar({ query, wildcardChar: '%', options: optionalOptions }),\n this.interpolateVariable\n );\n\n const interpolatedQuery: SQLQuery = {\n refId: 'tempvar',\n datasource: this.getRef(),\n rawSql,\n format: QueryFormat.Table,\n };\n\n const response = await this.runMetaQuery(interpolatedQuery, optionalOptions);\n return this.getResponseParser().transformMetricFindResponse(response);\n }\n\n async runSql<T extends object>(query: string, options?: RunSQLOptions) {\n const frame = await this.runMetaQuery({ rawSql: query, format: QueryFormat.Table, refId: options?.refId }, options);\n return new DataFrameView<T>(frame);\n }\n\n private runMetaQuery(request: Partial<SQLQuery>, options?: MetricFindQueryOptions): Promise<DataFrame> {\n const refId = request.refId || 'meta';\n const queries: DataQuery[] = [{ ...request, datasource: request.datasource || this.getRef(), refId }];\n\n return lastValueFrom(\n getBackendSrv()\n .fetch<BackendDataSourceResponse>({\n url: '/api/ds/query',\n method: 'POST',\n data: {\n from: options?.range?.from.valueOf().toString(),\n to: options?.range?.to.valueOf().toString(),\n queries,\n },\n requestId: refId,\n })\n .pipe(\n map((res: FetchResponse<BackendDataSourceResponse>) => {\n const rsp = toDataQueryResponse(res, queries);\n return rsp.data[0];\n })\n )\n );\n }\n\n testDatasource(): Promise<{ status: string; message: string }> {\n return lastValueFrom(\n getBackendSrv()\n .fetch({\n url: '/api/ds/query',\n method: 'POST',\n data: {\n from: '5m',\n to: 'now',\n queries: [\n {\n refId: 'A',\n intervalMs: 1,\n maxDataPoints: 1,\n datasource: this.getRef(),\n datasourceId: this.id,\n rawSql: 'SELECT 1',\n format: 'table',\n },\n ],\n },\n })\n .pipe(\n map(() => ({ status: 'success', message: 'Database Connection OK' })),\n catchError((err) => {\n // return of(toTestingStatus(err));\n return of(err);\n })\n )\n );\n }\n\n targetContainsTemplate(target: SQLQuery) {\n let queryWithoutMacros = target.rawSql;\n MACRO_NAMES.forEach((value) => {\n queryWithoutMacros = queryWithoutMacros?.replace(value, '') || '';\n });\n return this.templateSrv.containsTemplate(queryWithoutMacros);\n }\n}\n\ninterface RunSQLOptions extends MetricFindQueryOptions {\n refId?: string;\n}\n\ninterface MetricFindQueryOptions extends SearchFilterOptions {\n range?: TimeRange;\n}\n\nexport const SEARCH_FILTER_VARIABLE = '__searchFilter';\n\nexport const containsSearchFilter = (query: string | unknown): boolean =>\n query && typeof query === 'string' ? query.indexOf(SEARCH_FILTER_VARIABLE) !== -1 : false;\n\nexport const getSearchFilterScopedVar = (args: {\n query: string;\n wildcardChar: string;\n options?: SearchFilterOptions;\n}): ScopedVars => {\n const { query, wildcardChar } = args;\n if (!containsSearchFilter(query)) {\n return {};\n }\n\n let { options } = args;\n\n options = options || { searchFilter: '' };\n const value = options.searchFilter ? `${options.searchFilter}${wildcardChar}` : `${wildcardChar}`;\n\n return {\n __searchFilter: {\n value,\n text: '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EAAa,GAAI,IAAA;AAChC,EAAA,IAAI,CAAC,oBAAA,CAAqB,KAAK,CAAA,EAAG;AAChC,IAAA,OAAO,EAAC;AAAA,EACV;AAEA,EAAA,IAAI,EAAE,SAAQ,GAAI,IAAA;AAElB,EAAA,OAAA,GAAU,OAAA,IAAW,EAAE,YAAA,EAAc,EAAA,EAAG;AACxC,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,YAAA,GAAe,CAAA,EAAG,OAAA,CAAQ,YAAY,CAAA,EAAG,YAAY,CAAA,CAAA,GAAK,CAAA,EAAG,YAAY,CAAA,CAAA;AAE/F,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB;AAAA,MACd,KAAA;AAAA,MACA,IAAA,EAAM;AAAA;AACR,GACF;AACF;;;;"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import React, { ComponentProps,
|
|
1
|
+
import React, { ComponentProps, ReactElement, ReactNode, Component, ErrorInfo, PureComponent, FunctionComponent, HTMLProps } from 'react';
|
|
2
2
|
import { Input, Segment as Segment$1, monacoTypes, Monaco, ButtonProps, Field, PopoverContent, Switch, SelectCommonProps, InlineLabel } from '@grafana/ui';
|
|
3
|
-
import { DataSourceInstanceSettings,
|
|
4
|
-
import { DataSourceSrv, DataSourceWithBackend, TemplateSrv } from '@grafana/runtime';
|
|
3
|
+
import { DataSourceInstanceSettings, DataSourceJsonData, VariableSuggestion, SelectableValue, TimeRange, DataFrame, MetricFindValue, ThemeSpacingTokens, ScopedVars, VariableModel, DataFrameView, QueryEditorProps as QueryEditorProps$1, DataSourceSettings, RegistryItem, DataSourceApi, Registry, DataQuery as DataQuery$1, PanelData, DataQueryRequest, DataQueryResponse, LoadingState } from '@grafana/data';
|
|
5
4
|
import { JsonTree } from '@react-awesome-query-builder/ui';
|
|
6
5
|
import { DataQuery } from '@grafana/schema';
|
|
6
|
+
import { DataSourceWithBackend, TemplateSrv } from '@grafana/runtime';
|
|
7
7
|
import { SqlLanguage } from 'sql-formatter';
|
|
8
8
|
import { Grammar } from 'prismjs';
|
|
9
9
|
import { Observable } from 'rxjs';
|
|
@@ -46,8 +46,16 @@ interface DatePickerWithInputProps extends Omit<ComponentProps<typeof Input>, 'r
|
|
|
46
46
|
declare const DatePickerWithInput: (props: DatePickerWithInputProps) => React.JSX.Element;
|
|
47
47
|
|
|
48
48
|
interface Props$s {
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Receives the selected data source's list item (`uid`, `type`, `name`, `meta`). Call
|
|
51
|
+
* `getDataSourceInstanceSettings(ds.uid)` from `@grafana/plugin-compat` if you need the full settings.
|
|
52
|
+
*/
|
|
53
|
+
onChange: (ds: Pick<DataSourceInstanceSettings, 'uid' | 'type' | 'name' | 'meta'>) => void;
|
|
54
|
+
/**
|
|
55
|
+
* Reference to the selected data source, resolved the way Grafana does: uid, name, template variable or
|
|
56
|
+
* built-in. `null`/`undefined` resolves to the default data source.
|
|
57
|
+
*/
|
|
58
|
+
current?: string | null;
|
|
51
59
|
hideTextValue?: boolean;
|
|
52
60
|
onBlur?: () => void;
|
|
53
61
|
autoFocus?: boolean;
|
|
@@ -62,20 +70,7 @@ interface Props$s {
|
|
|
62
70
|
pluginId?: string;
|
|
63
71
|
noDefault?: boolean;
|
|
64
72
|
}
|
|
65
|
-
|
|
66
|
-
error?: string;
|
|
67
|
-
}
|
|
68
|
-
declare class DataSourcePicker extends PureComponent<Props$s, State$1> {
|
|
69
|
-
dataSourceSrv: DataSourceSrv;
|
|
70
|
-
static defaultProps: Partial<Props$s>;
|
|
71
|
-
state: State$1;
|
|
72
|
-
constructor(props: Props$s);
|
|
73
|
-
componentDidMount(): void;
|
|
74
|
-
onChange: (item: SelectableValue<string>) => void;
|
|
75
|
-
private getCurrentValue;
|
|
76
|
-
getDataSourceOptions(): Array<SelectableValue<string>>;
|
|
77
|
-
render(): React.JSX.Element;
|
|
78
|
-
}
|
|
73
|
+
declare function DataSourcePicker({ onChange, current: currentProp, hideTextValue, onBlur, autoFocus, openMenuOnFocus, placeholder, noDefault, }: Props$s): React.JSX.Element;
|
|
79
74
|
|
|
80
75
|
type DataLinkConfig = {
|
|
81
76
|
field: string;
|
|
@@ -778,6 +773,9 @@ declare abstract class SqlDatasource extends DataSourceWithBackend<SQLQuery, SQL
|
|
|
778
773
|
interpolateVariablesInQueries(queries: SQLQuery[], scopedVars: ScopedVars): SQLQuery[];
|
|
779
774
|
filterQuery(query: SQLQuery): boolean;
|
|
780
775
|
applyTemplateVariables(target: SQLQuery, scopedVars: ScopedVars): SQLQuery;
|
|
776
|
+
/**
|
|
777
|
+
* @deprecated `applyTemplateVariables` no longer calls this. Collapsing `''` to `'` breaks valid SQL string literals.
|
|
778
|
+
*/
|
|
781
779
|
clean(value: string): string;
|
|
782
780
|
metricFindQuery(query: string, optionalOptions?: MetricFindQueryOptions): Promise<MetricFindValue[]>;
|
|
783
781
|
runSql<T extends object>(query: string, options?: RunSQLOptions): Promise<DataFrameView<T>>;
|
|
@@ -1519,8 +1517,6 @@ declare function useHealthChecks(): {
|
|
|
1519
1517
|
retry: (uid: string) => void;
|
|
1520
1518
|
};
|
|
1521
1519
|
|
|
1522
|
-
declare function resolvePluginName(pluginType: string): string;
|
|
1523
|
-
|
|
1524
1520
|
type UseDatasourceSchemaResult = {
|
|
1525
1521
|
schema: DatasourceConfigSchema | null;
|
|
1526
1522
|
loading: boolean;
|
|
@@ -2016,5 +2012,5 @@ interface RequestLoopOptions<TQuery extends DataQuery$1 = DataQuery$1> {
|
|
|
2016
2012
|
*/
|
|
2017
2013
|
declare function getRequestLooper<T extends DataQuery$1 = DataQuery$1>(req: DataQueryRequest<T>, options: RequestLoopOptions<T>): Observable<DataQueryResponse>;
|
|
2018
2014
|
|
|
2019
|
-
export { AUTH_GROUP_IDS, AccessoryButton, AdvancedHttpSettings, Auth, AuthMethod, BINARY_OPERATIONS_KEY, CatalogSelector, CompletionItemInsertTextRule, CompletionItemKind, CompletionItemPriority, ConfigDescriptionLink, ConfigSection, ConfigSubSection, ConnectionSettings, CustomHeadersSettings, DataLink, DataLinks, DataSourceDescription, DataSourcePicker, DatasetSelector, DatasourceConfigWizard, DatasourceErrorBoundary, DatasourceWithAsyncBackend, DatePicker, DatePickerWithInput, DebounceInput, EditorField, EditorFieldGroup, EditorHeader, EditorList, EditorMode, EditorRow, EditorRows, EditorStack, EditorSwitch, FlexItem, GroupByRow, InlineSelect, InputGroup, LabelFilters, LinkedToken, MacroType, OperationExplainedBox, OperationList, OperationListExplained, OperationsEditorRow, OperatorType, QUERY_FORMAT_OPTIONS, QueryBuilderHints, QueryEditorMode, QueryEditorModeToggle, QueryEditorRow, QueryFormat, QueryHeaderSwitch, QueryModellerBase, QueryOptionGroup, ROOT_CONFIG_FIELDS, RawQuery, RunQueryButton, RunQueryButtons, SQLEditor, SQLEditorMode, SQLEditorTestUtils, SecureSocksProxyToggle, Segment, Space, SqlDatasource, SqlQueryEditor, StatementPosition, SuggestionKind, TLSSettings, TableSelector, TokenType, buildCelContext, buildCloneDatasourcePayload, buildCreateDatasourcePayload, buildUpdateDatasourcePayload, clearExpressionCache, computeVirtualFieldValues, convertLegacyAuthProps, datasourceToProvisioningYaml, evaluateCelDirect, evaluateCelExpression, evaluateComputedRead, evaluateDependsOn, extractFieldRefs, fetchConfigSchema, formKey, formatDate, formatYamlDiff, generateLLMHint, generateProvisioningTemplate, generateTroubleshootingFields, getConfigSchema, getRequestLooper, getStandardSQLCompletionProvider, getWatchedValue, language as grafanaStandardSQLLanguage, conf as grafanaStandardSQLLanguageConf, isAuthGroupId, isValidCelExpression, parseDependsOn, resolveActiveOverride, resolveGroups,
|
|
2020
|
-
export type { Aggregate, AllowedValuesValidationRule, Props$c as AuthProps, BaseFieldRef, BaseValidationRule, ColumnDefinition, ComputedMapping, ConfigField, ConfigGroup, CustomMeta, CustomValidationRule, DB, DataLinkConfig, DatasourceConfigSchema, DatasourceConfigWizardProps, DatasourceHealth, DatePickerProps, DatePickerWithInputProps, DebounceInputProps, DirectMapping, Expression, FieldEffect, FieldItemSchema, FieldKind, FieldOption, FieldOverride, FieldPack, FieldPackID, FieldPatch, FieldRelationship, FieldUI, FieldValidationRule, FormState, HealthState, IndexedPairMapping, Instruction, ItemCountValidationRule, LanguageCompletionProvider, LanguageDefinition, LengthValidationRule, MappingField, MetaDefinition, NameValue, PatternValidationRule, PositionContext, Props$s as Props, QueryBuilderLabelFilter, QueryBuilderOperation, QueryBuilderOperationDefinition, QueryBuilderOperationParamDef, QueryBuilderOperationParamEditorProps, QueryBuilderOperationParamValue, QueryEditorProps, QueryRowFilter, QueryStats, QueryWithDefaults, RAQBFieldTypes, RangeValidationRule, RelationshipType, RequestLoopOptions, ResolvedGroup, ResourceSelectorProps, ResponseParser, Role, RunQueryButtonsProps, RunningQueryInfo, SQLConnectionLimits, SQLExpression, SQLFilters, SQLMonarchLanguage, SQLOptions, SQLQuery, SQLSelectableValue, SchemaDefinition, SecureFieldState, SegmentProps, SqlQueryForInterpolation, SqlQueryModel,
|
|
2015
|
+
export { AUTH_GROUP_IDS, AccessoryButton, AdvancedHttpSettings, Auth, AuthMethod, BINARY_OPERATIONS_KEY, CatalogSelector, CompletionItemInsertTextRule, CompletionItemKind, CompletionItemPriority, ConfigDescriptionLink, ConfigSection, ConfigSubSection, ConnectionSettings, CustomHeadersSettings, DataLink, DataLinks, DataSourceDescription, DataSourcePicker, DatasetSelector, DatasourceConfigWizard, DatasourceErrorBoundary, DatasourceWithAsyncBackend, DatePicker, DatePickerWithInput, DebounceInput, EditorField, EditorFieldGroup, EditorHeader, EditorList, EditorMode, EditorRow, EditorRows, EditorStack, EditorSwitch, FlexItem, GroupByRow, InlineSelect, InputGroup, LabelFilters, LinkedToken, MacroType, OperationExplainedBox, OperationList, OperationListExplained, OperationsEditorRow, OperatorType, QUERY_FORMAT_OPTIONS, QueryBuilderHints, QueryEditorMode, QueryEditorModeToggle, QueryEditorRow, QueryFormat, QueryHeaderSwitch, QueryModellerBase, QueryOptionGroup, ROOT_CONFIG_FIELDS, RawQuery, RunQueryButton, RunQueryButtons, SQLEditor, SQLEditorMode, SQLEditorTestUtils, SecureSocksProxyToggle, Segment, Space, SqlDatasource, SqlQueryEditor, StatementPosition, SuggestionKind, TLSSettings, TableSelector, TokenType, buildCelContext, buildCloneDatasourcePayload, buildCreateDatasourcePayload, buildUpdateDatasourcePayload, clearExpressionCache, computeVirtualFieldValues, convertLegacyAuthProps, datasourceToProvisioningYaml, evaluateCelDirect, evaluateCelExpression, evaluateComputedRead, evaluateDependsOn, extractFieldRefs, fetchConfigSchema, formKey, formatDate, formatYamlDiff, generateLLMHint, generateProvisioningTemplate, generateTroubleshootingFields, getConfigSchema, getRequestLooper, getStandardSQLCompletionProvider, getWatchedValue, language as grafanaStandardSQLLanguage, conf as grafanaStandardSQLLanguageConf, isAuthGroupId, isValidCelExpression, parseDependsOn, resolveActiveOverride, resolveGroups, resolveRequiredFieldsGroup, toOption, useDatasourceSchema, useHealthChecks };
|
|
2016
|
+
export type { Aggregate, AllowedValuesValidationRule, Props$c as AuthProps, BaseFieldRef, BaseValidationRule, ColumnDefinition, ComputedMapping, ConfigField, ConfigGroup, CustomMeta, CustomValidationRule, DB, DataLinkConfig, DatasourceConfigSchema, DatasourceConfigWizardProps, DatasourceHealth, DatePickerProps, DatePickerWithInputProps, DebounceInputProps, DirectMapping, Expression, FieldEffect, FieldItemSchema, FieldKind, FieldOption, FieldOverride, FieldPack, FieldPackID, FieldPatch, FieldRelationship, FieldUI, FieldValidationRule, FormState, HealthState, IndexedPairMapping, Instruction, ItemCountValidationRule, LanguageCompletionProvider, LanguageDefinition, LengthValidationRule, MappingField, MetaDefinition, NameValue, PatternValidationRule, PositionContext, Props$s as Props, QueryBuilderLabelFilter, QueryBuilderOperation, QueryBuilderOperationDefinition, QueryBuilderOperationParamDef, QueryBuilderOperationParamEditorProps, QueryBuilderOperationParamValue, QueryEditorProps, QueryRowFilter, QueryStats, QueryWithDefaults, RAQBFieldTypes, RangeValidationRule, RelationshipType, RequestLoopOptions, ResolvedGroup, ResourceSelectorProps, ResponseParser, Role, RunQueryButtonsProps, RunningQueryInfo, SQLConnectionLimits, SQLExpression, SQLFilters, SQLMonarchLanguage, SQLOptions, SQLQuery, SQLSelectableValue, SchemaDefinition, SecureFieldState, SegmentProps, SqlQueryForInterpolation, SqlQueryModel, StatementPlacementProvider, StorageMapping, SuggestionKindProvider, Props$f as TLSSettingsProps, TableDefinition, TableFieldSchema, TableIdentifier, TableSchema, TargetLocation, TestQueryModel, UIComponent, UIWidth, ValidationResults, ValueType, VisualQuery, VisualQueryBinary, VisualQueryModeller };
|
package/dist/esm/index.js
CHANGED
|
@@ -40,7 +40,6 @@ export { AdvancedHttpSettings } from './components/ConfigEditor/AdvancedSettings
|
|
|
40
40
|
export { DatasourceConfigWizard } from './components/ConfigEditor/DatasourceConfigWizard/DatasourceConfigWizard.js';
|
|
41
41
|
export { DatasourceErrorBoundary } from './components/ConfigEditor/DatasourceConfigWizard/DatasourceErrorBoundary.js';
|
|
42
42
|
export { useHealthChecks } from './components/ConfigEditor/DatasourceConfigWizard/hooks/useHealthChecks.js';
|
|
43
|
-
export { resolvePluginName } from './components/ConfigEditor/DatasourceConfigWizard/resolvePluginName.js';
|
|
44
43
|
export { fetchConfigSchema, useDatasourceSchema } from './components/ConfigEditor/DatasourceConfigWizard/hooks/useDatasourceSchema.js';
|
|
45
44
|
export { buildCelContext, clearExpressionCache, evaluateCelDirect, evaluateCelExpression, extractFieldRefs, isValidCelExpression } from './components/ConfigEditor/DatasourceConfigWizard/cel.js';
|
|
46
45
|
export { AUTH_GROUP_IDS, computeVirtualFieldValues, evaluateComputedRead, evaluateDependsOn, formKey, getWatchedValue, isAuthGroupId, parseDependsOn, resolveActiveOverride, resolveGroups, resolveRequiredFieldsGroup } from './components/ConfigEditor/DatasourceConfigWizard/config.js';
|