export function mergeQueries()

in dashboard/new-dashboard/src/components/common/DataQueryExecutor.ts [216:245]


export function mergeQueries(queries: DataQuery[], configuration: DataQueryExecutorConfiguration | null): DataQuery[] {
  if (queries.length === 1) return queries
  const resultQueries: DataQuery[] = structuredClone(queries)
  const mergedNames = configuration?.seriesNames.map((name) => [name])

  let currentFilterField: string | null = null
  for (let i = 0; i < resultQueries.length; i++) {
    for (let j = i + 1; j < resultQueries.length; j++) {
      const matchingFilterField = getFilterNameForMerge(resultQueries[i], resultQueries[j])
      if ((currentFilterField == null && matchingFilterField != null) || (matchingFilterField === currentFilterField && matchingFilterField != null)) {
        currentFilterField = matchingFilterField
        resultQueries[i].filters = mergeFilters(resultQueries[i].filters, resultQueries[j].filters, resultQueries[i].fields)
        resultQueries.splice(j, 1) // remove the merged query
        //we need to merge the names of the queries as well to provide correct series names
        if (mergedNames) {
          mergedNames[i] = [...mergedNames[i], ...mergedNames[j]]
          mergedNames.splice(j, 1)
        }
        // Reset indices to re-evaluate with new list
        i = -1
        break // exit the inner loop
      }
    }
  }

  if (configuration != null && mergedNames != null) {
    configuration.seriesNames = mergedNames.flat(2)
  }
  return resultQueries
}