updateQueries.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { DataQuery, DataSourceApi, hasQueryExportSupport, hasQueryImportSupport } from '@grafana/data';
  2. import { isExpressionReference } from '@grafana/runtime/src/utils/DataSourceWithBackend';
  3. export async function updateQueries(
  4. nextDS: DataSourceApi,
  5. nextDSUidOrVariableExpression: string,
  6. queries: DataQuery[],
  7. currentDS?: DataSourceApi
  8. ): Promise<DataQuery[]> {
  9. let nextQueries = queries;
  10. const datasource = { type: nextDS.type, uid: nextDSUidOrVariableExpression };
  11. // we are changing data source type
  12. if (currentDS?.meta.id !== nextDS.meta.id) {
  13. // If changing to mixed do nothing
  14. if (nextDS.meta.mixed) {
  15. return queries;
  16. }
  17. // when both data sources support abstract queries
  18. else if (hasQueryExportSupport(currentDS) && hasQueryImportSupport(nextDS)) {
  19. const abstractQueries = await currentDS.exportToAbstractQueries(queries);
  20. nextQueries = await nextDS.importFromAbstractQueries(abstractQueries);
  21. }
  22. // when datasource supports query import
  23. else if (currentDS && nextDS.importQueries) {
  24. nextQueries = await nextDS.importQueries(queries, currentDS);
  25. }
  26. // Otherwise clear queries
  27. else {
  28. return [{ refId: 'A', datasource }];
  29. }
  30. }
  31. if (nextQueries.length === 0) {
  32. return [{ refId: 'A', datasource }];
  33. }
  34. // Set data source on all queries except expression queries
  35. return nextQueries.map((query) => {
  36. if (!isExpressionReference(query.datasource) && !nextDS.meta.mixed) {
  37. query.datasource = datasource;
  38. }
  39. return query;
  40. });
  41. }