table_model.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import _ from 'lodash';
  2. import { Column, TableData } from '@grafana/data';
  3. /**
  4. * Extends the standard Column class with variables that get
  5. * mutated in the angular table panel.
  6. */
  7. interface MutableColumn extends Column {
  8. title?: string;
  9. sort?: boolean;
  10. desc?: boolean;
  11. type?: string;
  12. }
  13. export default class TableModel implements TableData {
  14. columns: MutableColumn[];
  15. rows: any[];
  16. type: string;
  17. columnMap: any;
  18. constructor(table?: any) {
  19. this.columns = [];
  20. this.columnMap = {};
  21. this.rows = [];
  22. this.type = 'table';
  23. if (table) {
  24. if (table.columns) {
  25. for (const col of table.columns) {
  26. this.addColumn(col);
  27. }
  28. }
  29. if (table.rows) {
  30. for (const row of table.rows) {
  31. this.addRow(row);
  32. }
  33. }
  34. }
  35. }
  36. sort(options: { col: number; desc: boolean }) {
  37. if (options.col === null || this.columns.length <= options.col) {
  38. return;
  39. }
  40. this.rows.sort((a, b) => {
  41. a = a[options.col];
  42. b = b[options.col];
  43. // Sort null or undefined separately from comparable values
  44. return +(a == null) - +(b == null) || +(a > b) || -(a < b);
  45. });
  46. if (options.desc) {
  47. this.rows.reverse();
  48. }
  49. this.columns[options.col].sort = true;
  50. this.columns[options.col].desc = options.desc;
  51. }
  52. addColumn(col: Column) {
  53. if (!this.columnMap[col.text]) {
  54. this.columns.push(col);
  55. this.columnMap[col.text] = col;
  56. }
  57. }
  58. addRow(row: any[]) {
  59. this.rows.push(row);
  60. }
  61. }
  62. // Returns true if both rows have matching non-empty fields as well as matching
  63. // indexes where one field is empty and the other is not
  64. function areRowsMatching(columns: Column[], row: any[], otherRow: any[]) {
  65. let foundFieldToMatch = false;
  66. for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {
  67. if (row[columnIndex] !== undefined && otherRow[columnIndex] !== undefined) {
  68. if (row[columnIndex] !== otherRow[columnIndex]) {
  69. return false;
  70. }
  71. } else if (row[columnIndex] === undefined || otherRow[columnIndex] === undefined) {
  72. foundFieldToMatch = true;
  73. }
  74. }
  75. return foundFieldToMatch;
  76. }
  77. export function mergeTablesIntoModel(dst?: TableModel, ...tables: TableModel[]): TableModel {
  78. const model = dst || new TableModel();
  79. if (arguments.length === 1) {
  80. return model;
  81. }
  82. // Single query returns data columns and rows as is
  83. if (arguments.length === 2) {
  84. model.columns = tables[0].hasOwnProperty('columns') ? [...tables[0].columns] : [];
  85. model.rows = tables[0].hasOwnProperty('rows') ? [...tables[0].rows] : [];
  86. return model;
  87. }
  88. // Track column indexes of union: name -> index
  89. const columnNames: { [key: string]: any } = {};
  90. // Union of all non-value columns
  91. const columnsUnion = tables.slice().reduce(
  92. (acc, series) => {
  93. series.columns.forEach(col => {
  94. const { text } = col;
  95. if (columnNames[text] === undefined) {
  96. columnNames[text] = acc.length;
  97. acc.push(col);
  98. }
  99. });
  100. return acc;
  101. },
  102. [] as MutableColumn[]
  103. );
  104. // Map old column index to union index per series, e.g.,
  105. // given columnNames {A: 0, B: 1} and
  106. // data [{columns: [{ text: 'A' }]}, {columns: [{ text: 'B' }]}] => [[0], [1]]
  107. const columnIndexMapper = tables.map(series => series.columns.map(col => columnNames[col.text]));
  108. // Flatten rows of all series and adjust new column indexes
  109. const flattenedRows = tables.reduce(
  110. (acc, series, seriesIndex) => {
  111. const mapper = columnIndexMapper[seriesIndex];
  112. series.rows.forEach(row => {
  113. const alteredRow: MutableColumn[] = [];
  114. // Shifting entries according to index mapper
  115. mapper.forEach((to, from) => {
  116. alteredRow[to] = row[from];
  117. });
  118. acc.push(alteredRow);
  119. });
  120. return acc;
  121. },
  122. [] as MutableColumn[][]
  123. );
  124. // Merge rows that have same values for columns
  125. const mergedRows: { [key: string]: any } = {};
  126. const compactedRows = flattenedRows.reduce(
  127. (acc, row, rowIndex) => {
  128. if (!mergedRows[rowIndex]) {
  129. // Look from current row onwards
  130. let offset = rowIndex + 1;
  131. // More than one row can be merged into current row
  132. while (offset < flattenedRows.length) {
  133. // Find next row that could be merged
  134. const match = _.findIndex(flattenedRows, otherRow => areRowsMatching(columnsUnion, row, otherRow), offset);
  135. if (match > -1) {
  136. const matchedRow = flattenedRows[match];
  137. // Merge values from match into current row if there is a gap in the current row
  138. for (let columnIndex = 0; columnIndex < columnsUnion.length; columnIndex++) {
  139. if (row[columnIndex] === undefined && matchedRow[columnIndex] !== undefined) {
  140. row[columnIndex] = matchedRow[columnIndex];
  141. }
  142. }
  143. // Don't visit this row again
  144. mergedRows[match] = matchedRow;
  145. // Keep looking for more rows to merge
  146. offset = match + 1;
  147. } else {
  148. // No match found, stop looking
  149. break;
  150. }
  151. }
  152. acc.push(row);
  153. }
  154. return acc;
  155. },
  156. [] as MutableColumn[][]
  157. );
  158. model.columns = columnsUnion;
  159. model.rows = compactedRows;
  160. return model;
  161. }