@grafana/data#TableData TypeScript Examples

The following examples show how to use @grafana/data#TableData. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: file_export.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
export function convertTableDataToCsv(table: TableData, excel = false) {
  let text = formatSpecialHeader(excel);
  // add headline
  text += formatRow(table.columns.map((val: any) => val.title || val.text));
  // process data
  for (let i = 0; i < table.rows.length; i += 1) {
    text += formatRow(table.rows[i], i < table.rows.length - 1);
  }
  return text;
}
Example #2
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
processQueryResult(queries: any, res: any): DataQueryResponse {
    const data: TestData[] = [];
    let error: DataQueryError | undefined = undefined;

    for (const query of queries) {
      const results = res.data.results[query.refId];

      for (const t of results.tables || []) {
        const table = t as TableData;
        table.refId = query.refId;
        table.name = query.alias;
        data.push(table);
      }

      for (const series of results.series || []) {
        data.push({ target: series.name, datapoints: series.points, refId: query.refId, tags: series.tags });
      }

      if (results.error) {
        error = {
          message: results.error,
        };
      }
    }

    return { data, error };
  }
Example #3
Source File: table_model.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export default class TableModel implements TableData {
  columns: MutableColumn[];
  rows: any[];
  type: string;
  columnMap: any;
  refId: string;

  constructor(table?: any) {
    this.columns = [];
    this.columnMap = {};
    this.rows = [];
    this.type = 'table';

    if (table) {
      if (table.columns) {
        for (const col of table.columns) {
          this.addColumn(col);
        }
      }
      if (table.rows) {
        for (const row of table.rows) {
          this.addRow(row);
        }
      }
    }
  }

  sort(options: { col: number; desc: boolean }) {
    if (options.col === null || this.columns.length <= options.col) {
      return;
    }

    this.rows.sort((a, b) => {
      a = a[options.col];
      b = b[options.col];
      // Sort null or undefined separately from comparable values
      return +(a == null) - +(b == null) || +(a > b) || -(a < b);
    });

    if (options.desc) {
      this.rows.reverse();
    }

    this.columns[options.col].sort = true;
    this.columns[options.col].desc = options.desc;
  }

  addColumn(col: Column) {
    if (!this.columnMap[col.text]) {
      this.columns.push(col);
      this.columnMap[col.text] = col;
    }
  }

  addRow(row: any[]) {
    this.rows.push(row);
  }
}
Example #4
Source File: file_export.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export function exportTableDataToCsv(table: TableData, excel = false) {
  const text = convertTableDataToCsv(table, excel);
  saveSaveBlob(text, EXPORT_FILENAME);
}
Example #5
Source File: transformers.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
transformers['table'] = {
  description: 'Table',
  getColumns: data => {
    if (!data || data.length === 0) {
      return [];
    }

    // Single query returns data columns as is
    if (data.length === 1) {
      return [...data[0].columns];
    }

    const filteredData = tableDataFormatFilterer(data);

    // Track column indexes: name -> index
    const columnNames: any = {};

    // Union of all columns
    const columns = filteredData.reduce((acc: Column[], series: TableData) => {
      series.columns.forEach(col => {
        const { text } = col;
        if (columnNames[text] === undefined) {
          columnNames[text] = acc.length;
          acc.push(col);
        }
      });
      return acc;
    }, []);

    return columns;
  },
  transform: (data: any[], panel, model) => {
    if (!data || data.length === 0) {
      return;
    }
    const filteredData = tableDataFormatFilterer(data);
    const noTableIndex = _.findIndex(filteredData, d => 'columns' in d && 'rows' in d);
    if (noTableIndex < 0) {
      throw {
        message: `Result of query #${String.fromCharCode(
          65 + noTableIndex
        )} is not in table format, try using another transform.`,
      };
    }

    mergeTablesIntoModel(model, ...filteredData);
  },
};
Example #6
Source File: file_export.test.ts    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
describe('file_export', () => {
  const ctx: any = {};

  beforeEach(() => {
    ctx.seriesList = [
      {
        alias: 'series_1',
        datapoints: [
          [1, 1500026100000],
          [2, 1500026200000],
          [null, 1500026300000],
          [null, 1500026400000],
          [null, 1500026500000],
          [6, 1500026600000],
        ],
      },
      {
        alias: 'series_2',
        datapoints: [
          [11, 1500026100000],
          [12, 1500026200000],
          [13, 1500026300000],
          [15, 1500026500000],
        ],
      },
    ];

    ctx.timeFormat = 'X'; // Unix timestamp (seconds)
  });

  describe('when exporting series as rows', () => {
    it('should export points in proper order', () => {
      const text = fileExport.convertSeriesListToCsv(ctx.seriesList, { dateTimeFormat: ctx.timeFormat });
      const expectedText =
        '"Series";"Time";"Value"\r\n' +
        '"series_1";"1500026100";1\r\n' +
        '"series_1";"1500026200";2\r\n' +
        '"series_1";"1500026300";null\r\n' +
        '"series_1";"1500026400";null\r\n' +
        '"series_1";"1500026500";null\r\n' +
        '"series_1";"1500026600";6\r\n' +
        '"series_2";"1500026100";11\r\n' +
        '"series_2";"1500026200";12\r\n' +
        '"series_2";"1500026300";13\r\n' +
        '"series_2";"1500026500";15';

      expect(text).toBe(expectedText);
    });
  });

  describe('when exporting series as columns', () => {
    it('should export points in proper order', () => {
      const text = fileExport.convertSeriesListToCsvColumns(ctx.seriesList, { dateTimeFormat: ctx.timeFormat });
      const expectedText =
        '"Time";"series_1";"series_2"\r\n' +
        '"1500026100";1;11\r\n' +
        '"1500026200";2;12\r\n' +
        '"1500026300";null;13\r\n' +
        '"1500026400";null;null\r\n' +
        '"1500026500";null;15\r\n' +
        '"1500026600";6;null';

      expect(text).toBe(expectedText);
    });

    it('should not modify series.datapoints', () => {
      const expectedSeries1DataPoints = ctx.seriesList[0].datapoints.slice();
      const expectedSeries2DataPoints = ctx.seriesList[1].datapoints.slice();

      fileExport.convertSeriesListToCsvColumns(ctx.seriesList, { dateTimeFormat: ctx.timeFormat });

      expect(expectedSeries1DataPoints).toEqual(ctx.seriesList[0].datapoints);
      expect(expectedSeries2DataPoints).toEqual(ctx.seriesList[1].datapoints);
    });
  });

  describe('when exporting table data to csv', () => {
    it('should properly escape special characters and quote all string values', () => {
      const inputTable: any = {
        columns: [
          { title: 'integer_value' },
          { text: 'string_value' },
          { title: 'float_value' },
          { text: 'boolean_value' },
        ],
        rows: [
          [123, 'some_string', 1.234, true],
          [1000, 'some_string', 1.234567891, true],
          [0o765, 'some string with " in the middle', 1e-2, false],
          [0o765, 'some string with "" in the middle', 1e-2, false],
          [0o765, 'some string with """ in the middle', 1e-2, false],
          [0o765, '"some string with " at the beginning', 1e-2, false],
          [0o765, 'some string with " at the end"', 1e-2, false],
          [0x123, 'some string with \n in the middle', 10.01, false],
          [0b1011, 'some string with ; in the middle', -12.34, true],
          [123, 'some string with ;; in the middle', -12.34, true],
          [1234, '=a bogus formula  ', '-and another', '+another', '@ref'],
        ],
      };

      const returnedText = fileExport.convertTableDataToCsv(inputTable, false);

      const expectedText =
        '"integer_value";"string_value";"float_value";"boolean_value"\r\n' +
        '123;"some_string";1.234;true\r\n' +
        '1000;"some_string";1.234567891;true\r\n' +
        '501;"some string with "" in the middle";0.01;false\r\n' +
        '501;"some string with """" in the middle";0.01;false\r\n' +
        '501;"some string with """""" in the middle";0.01;false\r\n' +
        '501;"""some string with "" at the beginning";0.01;false\r\n' +
        '501;"some string with "" at the end""";0.01;false\r\n' +
        '291;"some string with \n in the middle";10.01;false\r\n' +
        '11;"some string with ; in the middle";-12.34;true\r\n' +
        '123;"some string with ;; in the middle";-12.34;true\r\n' +
        '1234;"\'=a bogus formula";"\'-and another";"\'+another";"\'@ref"';

      expect(returnedText).toBe(expectedText);
    });

    it('should decode HTML encoded characters', () => {
      const inputTable: TableData = {
        columns: [{ text: 'string_value' }],
        rows: [
          ['&quot;&amp;&auml;'],
          ['<strong>&quot;some html&quot;</strong>'],
          ['<a href="http://something/index.html">some text</a>'],
        ],
      };

      const returnedText = fileExport.convertTableDataToCsv(inputTable, false);

      const expectedText =
        '"string_value"\r\n' +
        '"""&รค"\r\n' +
        '"<strong>""some html""</strong>"\r\n' +
        '"<a href=""http://something/index.html"">some text</a>"';

      expect(returnedText).toBe(expectedText);
    });
  });
});