mirror of https://github.com/grafana/grafana
InfluxDB SQL: Provide raw query preview for query history (#75030)
* log the sql query * render the raw sql * Update rawQuery * unit testspull/75311/head
parent
d076f733e9
commit
a64bfdfb94
@ -0,0 +1,32 @@ |
||||
import { SQLQuery } from 'app/features/plugins/sql/types'; |
||||
|
||||
import { QueryEditorExpressionType } from '../../../../features/plugins/sql/expressions'; |
||||
|
||||
import { toRawSql } from './sqlUtil'; |
||||
|
||||
describe('toRawSql', () => { |
||||
it('should render sql properly', () => { |
||||
const expected = 'SELECT host FROM iox.value1 LIMIT 50'; |
||||
const testQuery: SQLQuery = { |
||||
refId: 'A', |
||||
sql: { |
||||
limit: 50, |
||||
columns: [ |
||||
{ |
||||
parameters: [ |
||||
{ |
||||
name: 'host', |
||||
type: QueryEditorExpressionType.FunctionParameter, |
||||
}, |
||||
], |
||||
type: QueryEditorExpressionType.Function, |
||||
}, |
||||
], |
||||
}, |
||||
dataset: 'iox', |
||||
table: 'value1', |
||||
}; |
||||
const result = toRawSql(testQuery); |
||||
expect(result).toEqual(expected); |
||||
}); |
||||
}); |
||||
@ -0,0 +1,45 @@ |
||||
import { isEmpty } from 'lodash'; |
||||
|
||||
import { SQLQuery } from 'app/features/plugins/sql/types'; |
||||
import { createSelectClause, haveColumns } from 'app/features/plugins/sql/utils/sql.utils'; |
||||
|
||||
export function toRawSql({ sql, dataset, table }: SQLQuery): string { |
||||
let rawQuery = ''; |
||||
|
||||
// Return early with empty string if there is no sql column
|
||||
if (!sql || !haveColumns(sql.columns)) { |
||||
return rawQuery; |
||||
} |
||||
|
||||
rawQuery += createSelectClause(sql.columns); |
||||
|
||||
if (dataset && table) { |
||||
rawQuery += `FROM ${dataset}.${table} `; |
||||
} |
||||
|
||||
if (sql.whereString) { |
||||
rawQuery += `WHERE ${sql.whereString} `; |
||||
} |
||||
|
||||
if (sql.groupBy?.[0]?.property.name) { |
||||
const groupBy = sql.groupBy.map((g) => g.property.name).filter((g) => !isEmpty(g)); |
||||
rawQuery += `GROUP BY ${groupBy.join(', ')} `; |
||||
} |
||||
|
||||
if (sql.orderBy?.property.name) { |
||||
rawQuery += `ORDER BY ${sql.orderBy.property.name} `; |
||||
} |
||||
|
||||
if (sql.orderBy?.property.name && sql.orderByDirection) { |
||||
rawQuery += `${sql.orderByDirection} `; |
||||
} |
||||
|
||||
// Although LIMIT 0 doesn't make sense, it is still possible to have LIMIT 0
|
||||
if (isLimit(sql.limit)) { |
||||
rawQuery += `LIMIT ${sql.limit}`; |
||||
} |
||||
|
||||
return rawQuery; |
||||
} |
||||
|
||||
const isLimit = (limit: number | undefined): boolean => limit !== undefined && limit >= 0; |
||||
Loading…
Reference in new issue