Files
grafana/public/app/features/query/components/QueryGroup.tsx

444 lines
13 KiB
TypeScript
Raw Normal View History

import { css } from '@emotion/css';
import React, { PureComponent } from 'react';
import { Unsubscribable } from 'rxjs';
import {
CoreApp,
DataSourceApi,
DataSourceInstanceSettings,
getDefaultTimeRange,
LoadingState,
PanelData,
} from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { getDataSourceSrv, locationService } from '@grafana/runtime';
import { DataQuery } from '@grafana/schema';
import { Button, CustomScrollbar, HorizontalGroup, InlineFormLabel, Modal, stylesFactory } from '@grafana/ui';
2018-12-19 10:53:14 +01:00
import { PluginHelp } from 'app/core/components/PluginHelp/PluginHelp';
import config from 'app/core/config';
import { backendSrv } from 'app/core/services/backend_srv';
import { addQuery, queryIsEmpty } from 'app/core/utils/query';
import { DataSourceModal } from 'app/features/datasources/components/picker/DataSourceModal';
import { DataSourcePicker } from 'app/features/datasources/components/picker/DataSourcePicker';
import { dataSource as expressionDatasource } from 'app/features/expressions/ExpressionDatasource';
import { DashboardQueryEditor, isSharedDashboardQuery } from 'app/plugins/datasource/dashboard';
import { GrafanaQuery } from 'app/plugins/datasource/grafana/types';
import { QueryGroupOptions } from 'app/types';
import { PanelQueryRunner } from '../state/PanelQueryRunner';
import { updateQueries } from '../state/updateQueries';
2018-11-20 14:17:03 +01:00
import { GroupActionComponents } from './QueryActionComponent';
import { QueryEditorRows } from './QueryEditorRows';
import { QueryGroupOptionsEditor } from './QueryGroupOptions';
export interface Props {
queryRunner: PanelQueryRunner;
options: QueryGroupOptions;
onOpenQueryInspector?: () => void;
onRunQueries: () => void;
onOptionsChange: (options: QueryGroupOptions) => void;
}
interface State {
dataSource?: DataSourceApi;
dsSettings?: DataSourceInstanceSettings;
queries: DataQuery[];
helpContent: React.ReactNode;
2018-12-12 06:52:08 +01:00
isLoadingHelp: boolean;
2018-12-11 17:03:38 +01:00
isPickerOpen: boolean;
isDataSourceModalOpen: boolean;
data: PanelData;
isHelpOpen: boolean;
defaultDataSource?: DataSourceApi;
scrollElement?: HTMLDivElement;
}
export class QueryGroup extends PureComponent<Props, State> {
Chore: Remove angular dependency from backendSrv (#20999) * Chore: Remove angular dependency from backendSrv * Refactor: Naive soultion for logging out unauthorized users * Refactor: Restructures to different streams * Refactor: Restructures datasourceRequest * Refactor: Flipped back if statement * Refactor: Extracted getFromFetchStream * Refactor: Extracts toFailureStream operation * Refactor: Fixes issue when options.params contains arrays * Refactor: Fixes broken test (but we need a lot more) * Refactor: Adds explaining comments * Refactor: Adds latest RxJs version so cancellations work * Refactor: Cleans up the takeUntil code * Refactor: Adds tests for request function * Refactor: Separates into smaller functions * Refactor: Adds last error tests * Started to changed so we require getBackendSrv from the @grafana-runtime when applicable. * Using the getBackendSrv from @grafana/runtime. * Changed so we use the getBackendSrv from the @grafana-runtime when possible. * Fixed so Server Admin -> Orgs works again. * Removed unused dependency. * Fixed digest issues on the Server Admin -> Users page. * Fix: Fixes digest problems in Playlists * Fix: Fixes digest issues in VersionHistory * Tests: Fixes broken tests * Fix: Fixes digest issues in Alerting => Notification channels * Fixed digest issues on the Intive page. * Fixed so we run digest after password reset email sent. * Fixed digest issue when trying to sign up account. * Fixed so the Server Admin -> Edit Org works with backendSrv * Fixed so Server Admin -> Users works with backend srv. * Fixed digest issues in Server Admin -> Orgs * Fix: Fixes digest issues in DashList plugin * Fixed digest issues on Server Admin -> users. * Fix: Fixes digest issues with Snapshots * Fixed digest issue when deleting a user. * Fix: Fixes digest issues with dashLink * Chore: Changes RxJs version to 6.5.4 which includes the same cancellation fix * Fix: Fixes digest issue when toggling folder in manage dashboards * Fix: Fixes bug in executeInOrder * Fix: Fixes digest issue with CreateFolderCtrl and FolderDashboardsCtrl * Fix: Fixes tslint error in test * Refactor: Changes default behaviour for emitted messages as before migration * Fix: Fixes various digest issues when saving, starring or deleting dashboards * Fix: Fixes digest issues with FolderPickerCtrl * Fixed digest issue. * Fixed digest issues. * Fixed issues with angular digest. * Removed the this.digest pattern. Co-authored-by: Hugo Häggmark <hugo.haggmark@gmail.com> Co-authored-by: Marcus Andersson <systemvetaren@gmail.com>
2020-01-21 09:08:07 +00:00
backendSrv = backendSrv;
dataSourceSrv = getDataSourceSrv();
querySubscription: Unsubscribable | null = null;
state: State = {
isDataSourceModalOpen: !!locationService.getSearchObject().firstPanel,
isLoadingHelp: false,
helpContent: null,
isPickerOpen: false,
isHelpOpen: false,
queries: [],
data: {
state: LoadingState.NotStarted,
series: [],
timeRange: getDefaultTimeRange(),
},
};
async componentDidMount() {
const { options, queryRunner } = this.props;
this.querySubscription = queryRunner.getData({ withTransforms: false, withFieldConfig: false }).subscribe({
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 17:28:46 +02:00
next: (data: PanelData) => this.onPanelDataUpdate(data),
});
this.setNewQueriesAndDatasource(options);
// Clean up the first panel flag since the modal is now open
if (!!locationService.getSearchObject().firstPanel) {
locationService.partial({ firstPanel: null }, true);
}
}
componentWillUnmount() {
if (this.querySubscription) {
this.querySubscription.unsubscribe();
this.querySubscription = null;
}
}
async componentDidUpdate() {
const { options } = this.props;
const currentDS = await getDataSourceSrv().get(options.dataSource);
if (this.state.dataSource && currentDS.uid !== this.state.dataSource?.uid) {
this.setNewQueriesAndDatasource(options);
}
}
async setNewQueriesAndDatasource(options: QueryGroupOptions) {
try {
const ds = await this.dataSourceSrv.get(options.dataSource);
const dsSettings = this.dataSourceSrv.getInstanceSettings(options.dataSource);
const defaultDataSource = await this.dataSourceSrv.get();
const datasource = ds.getRef();
const queries = options.queries.map((q) => ({
...(queryIsEmpty(q) && ds?.getDefaultQuery?.(CoreApp.PanelEditor)),
datasource,
...q,
}));
this.setState({
queries,
dataSource: ds,
dsSettings,
defaultDataSource,
});
} catch (error) {
console.log('failed to load data source', error);
}
}
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 17:28:46 +02:00
onPanelDataUpdate(data: PanelData) {
this.setState({ data });
}
onChangeDataSource = async (
newSettings: DataSourceInstanceSettings,
defaultQueries?: DataQuery[] | GrafanaQuery[]
) => {
const { dsSettings } = this.state;
const currentDS = dsSettings ? await getDataSourceSrv().get(dsSettings.uid) : undefined;
const nextDS = await getDataSourceSrv().get(newSettings.uid);
// We need to pass in newSettings.uid as well here as that can be a variable expression and we want to store that in the query model not the current ds variable value
const queries = defaultQueries || (await updateQueries(nextDS, newSettings.uid, this.state.queries, currentDS));
const dataSource = await this.dataSourceSrv.get(newSettings.name);
SQL Datasources: Reinstate SQL data source behavior around database selection when default configured databases already exist (#65659) * badlm0mma/sql_datasource_update/ initial notes * baldm0mma/sql_datasource_update/ solution * baldm0mma/sql_datasource_update/ clean datasetSelector * baldm0mma/sql_datasource_update/ clean up queryEditor.tsx * baldm0mma/sql_datasource_update/ clewan up queryHeader.tsx * baldm0mma/sql_datasource_update/ clean up tableSelector.tsx * baldm0mma/sql_datasource_update/ clean up mysqlDatasource.ts * baldm0mma/sql_datasource_update/ clean up configurationEditor.tsx * baldm0mma/sql_datasource_update/ rem conlog from queryEditor.tsx * baldm0mma/sql_datasource_update/ rem conlog from queryEditor.tsx * baldm0mma/sql_datasource_update/ remove conlog in tableSelector.tsx * baldm0mma/sql_datasource_update/ rem conlog in sqlDatasource.ts * baldm0mma/sql_datasource_update/ update deafult database value in sqlDatasource.ts * baldm0mma/sql_datasource_update/ update logic to accomidate no preconfig * baldm0mma/sql_datasource_update/ update props * baldm0mma/sql_datasource_update/ update prop names * baldm0mma/sql_datasource_update/ update prop names in tableSelector * baldm0mma/sql_datasource_update/ update annos in datasetSelector * baldm0mma/sql_datasource_update/ update naming * baldm0mma/sql_datasource_update/ update to standard langauae * baldm0mma/sql_datasource_update/ update prop names * baldm0mma/sql_datasource_update/ update annos in datasetSelector * baldm0mma/sql_datasource_update/ remove unused import in tableSelector.tsx * baldm0mma/sql_datasource_update/ remove addDefaultdataset * baldm0mma/sql_datasource_update/ reset query when needed * baldm0mma/sql_datasource_update/ update asymc return val * baldm0mma/sql_datasource_update/ remove psql query editor * baldm0mma/sql_datasource_update/ remove con logs in defaults.ts * baldm0mma/sql_datasource_update/ revert postgres changes * baldm0mma/sql_datasource_update/ update postgres naming * baldm0mma/sql_datasource_update/ add altert * baldm0mma/sql_datasource_update/ update annos and add alerts and alert logic * baldm0mma/sql_datasource_update/ update postgres nomenclature * baldm0mma/sql_datasource_update/ update annos and remove con logs * baldm0mma/sql_datasource_update/ update nomenclature * baldm0mma/sql_datasource_update/ drone fix * baldm0mma/sql_datasource_update/ export and format * baldm0mma/sql_datasource_update/ update docs for mysql datasource with dataset dropdown disable info * baldm0mma/sql_datasource_update/ update mssql docs * baldm0mma/sql_datasource_update/ update postgres docs and alert logic * baldm0mma/sql_datasource_update/ add tests * baldm0mma/sql_datasource_update/ update docs * baldm0mma/sql_datasource_update/ update test names * baldm0mma/sql_datasource_update/ update alert language * baldm0mma/sql_datasource_update/ correct spelling * baldm0mma/sql_datasource_update/ update postgres query builder image * baldm0mma/sql_datasource_update/ update annos * baldm0mma/sql_datasource_update/ update tests * baldm0mma/sql_datasource_update/ docs updated * baldm0mma/sql_datsource_update/ refactor determinePlaceholder * Update public/app/features/plugins/sql/components/QueryEditor.tsx spelling Co-authored-by: Zoltán Bedi <zoltan.bedi@gmail.com> * Update public/app/features/plugins/sql/components/QueryEditor.tsx spelling Co-authored-by: Zoltán Bedi <zoltan.bedi@gmail.com> * baldm0mma/sql_datasource_update/ remove superfluous cleanup data from tests * baldm0mma/sql_datasource_update/ update spelling * Update public/app/features/plugins/sql/components/SqlComponents.test.tsx spelling Co-authored-by: Zoltán Bedi <zoltan.bedi@gmail.com> * baldm0mma/sql_datasource_update/ add logic to prevent db call for tables if dataset it nullish * baldm0mma/sql_datasource_update/ update alert tests * baldm0mma/sql_datasource_update/ update button text * baldm0mma/sql_datasource_update/ update tests to preferred standard * baldm0mma/sql_datasource_update/add feature flag * baldm0mma/sql_datasource_update/ update mssql docs * baldm0mma/sql_datasource_update/ add feature flag to registry * baldm0mma/sql_datasource_update/ adjust table and dataset dropdown logic * baldm0mma/sql_datasource_update/ update testing to deal with feature flag * baldm0mma/sql_datasource_update/ update wioth cascadeDisable * baldm0mma/sql_datasource_update/ update naming * baldm0mma/sql_datasource_update/ update tests to reflect enabled feature flag * baldm0mma/sql_datasource_update/ update annotations * baldm0mma/sql_datasource_update/ update annos in queryEd * baldm0mma/sql_datasource_update/ update test names * baldm0mma/sql_datasource_update/ update anno issues * baldm0mma/slq_datasource_update/ add query to sqlDatasource with error * baldm0mma/sql_datasource_update/ update docs language * baldm0mma/sql_datasource_update/ remove notes to self * baldm0mma/sql_datasource_update/ add QueryEditorFeatureFlag.utils.ts * baldm0mma/sql_datasource_update/ update database into json * baldm0mma/sql_datasource_update/ found file * Update docs/sources/datasources/mssql/query-editor/index.md Co-authored-by: lwandz13 <126723338+lwandz13@users.noreply.github.com> * baldm0mma/sql_datasource_update/ update feature flag and toggles * baldm0mma/sql_datasource_update/ add hasConfigIssue, update annos, rethink disable logic * baldm0mma/sql_datasource_update/ update warning language * baldm0mma/sql_datasource_update/ update button content * baldm0mma/sql_datasource_update/ update jsonData logic in frontendsettings.go * baldm0mma/sql_datasource_update/ update jsonData logic * baldm0mma/sql_datasource_update/ update annos in frontendsettings.go * baldm0mma/sql_datasource_update/ update sql editor docs * baldm0mma/sql_datasource_update/ update mysql docs * baldm0mma/sql_datasource_update/ update postgres docs * baldm0mma/sql_datasource_update/ remove unused code in datasetSelector.tsx * baldm0mma/sql_datasource_update/ update syntax conventions * baldm0mma/sql_datasource_update/ add logs * baldm0mma/sql_datasource_update/ remove unused code * baldm0mma/sql_datasource_update/ remove conlogs * baldm0mma/sql_datasource_update/ update tests * baldm0mma/sql_datasource_update/ add second error to query * baldm0mma/sql_datasource_update/ run make gen-cue * baldm0mma/sql_database_update/ lint registry * baldm0mma/sql_datasource_update/ update registry * baldm0mma/sql_datasource_update/ upate datasource logic * baldm0mma/sql_datasource_update/ add logs * baldm0mma/sql_datasource_update/ add comms to self * baldm0mma/sql_datasource_update/ comment out false pos tests, and add investigatory comments * baldm0mma/sql_database_update/ update query error to only test for config change if query was made in "builder" mode * baldm0mma/sql_datasource_update/ update annos in frontendsettings.go * baldm0mma/sql_datasource_update/ update error logic to datasource * baldm0mma/sql_datasource_update/ remove alerts from query editor * baldm0mma/sql_datasource_update/ remove unused imports * baldm0mma/sql_datasource_update/ update tests * baldm0mma/sql_datasource_update/ remove comments * baldm0mma/sql_datasource_update/ remove logs in queryGroup.tsx * baldm0mma/sql_datasource_update/ remove outdated annotation in datasetSelector.tsx * baldm0mma/sql_datasource_update/ remove superfluous test and update test description * baldm0mma/sql_datasource_update/ remove feature flag * baldm0mma/sql_datasource_update/ add back feature flag * baldm0mma/sql_datasource_update/ update to enums * baldm0mma/sql_datasource_update/ update panel caps * baldm0mma/sql_datasource_update/ update dataset selector to default update the database correctly * baldm0mma/sql_datasource_update/ move onChange into conditional * baldm0mma/sql_datasource_update/ add logic for previous datasets choice * baldm0mma/sql_datasource_update/ add back previous logic for assigning default datasets * baldm0mma/sql_datasource_update/ update useEffect dep array * baldm0mma/sql_datasource_update/ remove feature toggle * baldm0mma/sql_datasource_update/ add feature toggle --------- Co-authored-by: Zoltán Bedi <zoltan.bedi@gmail.com> Co-authored-by: lwandz13 <126723338+lwandz13@users.noreply.github.com>
2023-06-06 10:28:52 -06:00
this.onChange({
queries,
dataSource: {
name: newSettings.name,
uid: newSettings.uid,
type: newSettings.meta.id,
default: newSettings.isDefault,
},
});
this.setState({
queries,
dataSource: dataSource,
dsSettings: newSettings,
Inspector: move `Panel JSON` and query inspector to the inspector (#23354) * move Panel JSON to inspector * move Panel JSON to inspector * update test * use stats display options * move query inspector to inspector * open inspector from the queries section * subscribe to results * subscribe to results * open the right tab * apply review feedback * update menus (inspect tabs) * Dashboard: extend dashnav to add custom content (#23433) * Dashlist: Fixed dashlist broken in edit mode (#23426) * Chore: Fix bunch of strict null error to fix master CI (#23443) * Fix bunch of null error * Fix failing test * Another test fix * Docs: Add SQL region annotation examples (#23268) Add region annotation examples for SQL data sources in docs. Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> * Docs: Update contributing doc to install node@12. (#23450) * NewPanelEdit: Minor style and description tweaks, AND PanelQueryRunner & autoMinMax (#23445) * NewPanelEdit: Minor style and description tweaks * Removed the worst snapshot of all time * ReactTable: adds color text to field options (#23427) * Feature: adds text color field config * Refactor: created an extension point * Refactor: uses HOC for extension instead * Fix: fixes background styling from affecting cells without display.color * Chore: export OptionsUIRegistryBuilder on grafana/data (#23444) * export the ui registry * add to utils index also * DataLinks: Do not full page reload data links links (#23429) * Templating: Fix global variable "__org.id" (#23362) * Fixed global variable __org.id value * correct orgId value * reverted the change as variables moved to new file * Chore: reduce null check errors to 788 (currently over 798) (#23449) * Fixed ts errors so build will succeed * Update packages/grafana-data/src/types/graph.ts Co-Authored-By: Ryan McKinley <ryantxu@gmail.com> * Feedback from code review * Leaving out trivial typing's * Fix error with color being undefined now. * fix test with timezone issue * Fixed test Co-authored-by: Ryan McKinley <ryantxu@gmail.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com> * Cloudwatch: prefer webIdentity over EC2 role (#23452) * Plugins: add a signature status flag (#23420) * Progress * fixed button * Final touches * now works from edit mode * fix layout * show raw objects * move query inspector buttons to the bottom * update snapshot * Updated design * Made full page reload work * Fixed minor style issue * Updated * More fixes * Removed unused imports * Updated * Moved to data tab out to seperate component * fixed ts issue Co-authored-by: Torkel Ödegaard <torkel@grafana.com> Co-authored-by: Agnès Toulet <35176601+AgnesToulet@users.noreply.github.com> Co-authored-by: Andrej Ocenas <mr.ocenas@gmail.com> Co-authored-by: Alexandre de Verteuil <alexandre@grafana.com> Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> Co-authored-by: Cyril Tovena <cyril.tovena@gmail.com> Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Vikky Omkar <vikkyomkar@gmail.com> Co-authored-by: Stephanie Closson <srclosson@gmail.com> Co-authored-by: Dário Nascimento <dfrnascimento@gmail.com>
2020-04-15 07:51:51 -07:00
});
if (defaultQueries) {
this.props.onRunQueries();
}
};
2018-12-11 13:36:44 +01:00
onAddQueryClick = () => {
const { queries } = this.state;
this.onQueriesChange(addQuery(queries, this.newQuery()));
this.onScrollBottom();
2018-12-11 13:36:44 +01:00
};
newQuery(): Partial<DataQuery> {
const { dsSettings, defaultDataSource } = this.state;
const ds = !dsSettings?.meta.mixed ? dsSettings : defaultDataSource;
return {
...this.state.dataSource?.getDefaultQuery?.(CoreApp.PanelEditor),
datasource: { uid: ds?.uid, type: ds?.type },
};
}
onChange(changedProps: Partial<QueryGroupOptions>) {
this.props.onOptionsChange({
...this.props.options,
...changedProps,
});
}
onAddExpressionClick = () => {
this.onQueriesChange(addQuery(this.state.queries, expressionDatasource.newQuery()));
this.onScrollBottom();
};
onScrollBottom = () => {
setTimeout(() => {
if (this.state.scrollElement) {
this.state.scrollElement.scrollTo({ top: 10000 });
}
}, 20);
2018-12-11 13:36:44 +01:00
};
onUpdateAndRun = (options: QueryGroupOptions) => {
this.props.onOptionsChange(options);
this.props.onRunQueries();
};
renderTopSection(styles: QueriesTabStyles) {
const { onOpenQueryInspector, options } = this.props;
const { dataSource, data } = this.state;
2018-11-09 15:49:55 +01:00
return (
<div>
<div className={styles.dataSourceRow}>
<InlineFormLabel htmlFor="data-source-picker" width={'auto'}>
Data source
</InlineFormLabel>
<div className={styles.dataSourceRowItem}>{this.renderDataSourcePickerWithPrompt()}</div>
{dataSource && (
<>
<div className={styles.dataSourceRowItem}>
<Button
variant="secondary"
icon="question-circle"
title="Open data source help"
onClick={this.onOpenHelp}
data-testid="query-tab-help-button"
/>
</div>
<div className={styles.dataSourceRowItemOptions}>
<QueryGroupOptionsEditor
options={options}
dataSource={dataSource}
data={data}
onChange={this.onUpdateAndRun}
/>
</div>
{onOpenQueryInspector && (
<div className={styles.dataSourceRowItem}>
<Button
variant="secondary"
onClick={onOpenQueryInspector}
aria-label={selectors.components.QueryTab.queryInspectorButton}
>
Query inspector
</Button>
</div>
)}
</>
)}
</div>
</div>
);
}
onOpenHelp = () => {
this.setState({ isHelpOpen: true });
};
onCloseHelp = () => {
this.setState({ isHelpOpen: false });
2018-12-11 17:03:38 +01:00
};
2018-11-09 15:49:55 +01:00
onCloseDataSourceModal = () => {
this.setState({ isDataSourceModalOpen: false });
};
renderDataSourcePickerWithPrompt = () => {
const { isDataSourceModalOpen } = this.state;
const commonProps = {
metrics: true,
mixed: true,
dashboard: true,
variables: true,
current: this.props.options.dataSource,
uploadFile: true,
onChange: async (ds: DataSourceInstanceSettings, defaultQueries?: DataQuery[] | GrafanaQuery[]) => {
await this.onChangeDataSource(ds, defaultQueries);
this.onCloseDataSourceModal();
},
};
return (
<>
{isDataSourceModalOpen && config.featureToggles.advancedDataSourcePicker && (
<DataSourceModal {...commonProps} onDismiss={this.onCloseDataSourceModal}></DataSourceModal>
)}
<DataSourcePicker {...commonProps} />
</>
);
};
onAddQuery = (query: Partial<DataQuery>) => {
const { dsSettings, queries } = this.state;
this.onQueriesChange(addQuery(queries, query, { type: dsSettings?.type, uid: dsSettings?.uid }));
this.onScrollBottom();
};
onQueriesChange = (queries: DataQuery[] | GrafanaQuery[]) => {
this.onChange({ queries });
this.setState({ queries });
};
renderQueries(dsSettings: DataSourceInstanceSettings) {
const { onRunQueries } = this.props;
const { data, queries } = this.state;
if (isSharedDashboardQuery(dsSettings.name)) {
return (
<DashboardQueryEditor
queries={queries}
panelData={data}
onChange={this.onQueriesChange}
onRunQueries={onRunQueries}
/>
);
}
return (
<div aria-label={selectors.components.QueryTab.content}>
<QueryEditorRows
queries={queries}
dsSettings={dsSettings}
onQueriesChange={this.onQueriesChange}
onAddQuery={this.onAddQuery}
onRunQueries={onRunQueries}
data={data}
/>
</div>
);
}
isExpressionsSupported(dsSettings: DataSourceInstanceSettings): boolean {
return (dsSettings.meta.alerting || dsSettings.meta.mixed) === true;
}
renderExtraActions() {
return GroupActionComponents.getAllExtraRenderAction()
.map((action, index) =>
action({
onAddQuery: this.onAddQuery,
onChangeDataSource: this.onChangeDataSource,
key: index,
})
)
.filter(Boolean);
}
renderAddQueryRow(dsSettings: DataSourceInstanceSettings, styles: QueriesTabStyles) {
2023-06-16 15:12:52 +02:00
const showAddButton = !isSharedDashboardQuery(dsSettings.name);
return (
<HorizontalGroup spacing="md" align="flex-start">
{showAddButton && (
<Button
icon="plus"
onClick={this.onAddQueryClick}
variant="secondary"
aria-label={selectors.components.QueryTab.addQuery}
data-testid="query-tab-add-query"
>
Query
</Button>
)}
{config.expressionsEnabled && this.isExpressionsSupported(dsSettings) && (
2022-01-20 08:52:36 -05:00
<Button
icon="plus"
onClick={this.onAddExpressionClick}
variant="secondary"
className={styles.expressionButton}
data-testid="query-tab-add-expression"
2022-01-20 08:52:36 -05:00
>
<span>Expression&nbsp;</span>
</Button>
)}
{this.renderExtraActions()}
</HorizontalGroup>
);
}
setScrollRef = (scrollElement: HTMLDivElement): void => {
this.setState({ scrollElement });
};
render() {
const { isHelpOpen, dsSettings } = this.state;
const styles = getStyles();
2018-12-12 06:52:08 +01:00
return (
<CustomScrollbar autoHeightMin="100%" scrollRefCallback={this.setScrollRef}>
<div className={styles.innerWrapper}>
{this.renderTopSection(styles)}
{dsSettings && (
<>
<div className={styles.queriesWrapper}>{this.renderQueries(dsSettings)}</div>
{this.renderAddQueryRow(dsSettings, styles)}
{isHelpOpen && (
<Modal title="Data source help" isOpen={true} onDismiss={this.onCloseHelp}>
<PluginHelp pluginId={dsSettings.meta.id} />
</Modal>
)}
</>
)}
</div>
</CustomScrollbar>
);
}
}
const getStyles = stylesFactory(() => {
const { theme } = config;
return {
innerWrapper: css`
display: flex;
flex-direction: column;
padding: ${theme.spacing.md};
`,
dataSourceRow: css`
display: flex;
margin-bottom: ${theme.spacing.md};
`,
dataSourceRowItem: css`
margin-right: ${theme.spacing.inlineFormMargin};
`,
dataSourceRowItemOptions: css`
flex-grow: 1;
margin-right: ${theme.spacing.inlineFormMargin};
`,
queriesWrapper: css`
padding-bottom: 16px;
`,
expressionWrapper: css``,
expressionButton: css`
margin-right: ${theme.spacing.sm};
`,
};
});
type QueriesTabStyles = ReturnType<typeof getStyles>;