postgres_query_model.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { find, map } from 'lodash';
  2. import { ScopedVars } from '@grafana/data';
  3. import { TemplateSrv } from '@grafana/runtime';
  4. export default class PostgresQueryModel {
  5. target: any;
  6. templateSrv: any;
  7. scopedVars: any;
  8. /** @ngInject */
  9. constructor(target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {
  10. this.target = target;
  11. this.templateSrv = templateSrv;
  12. this.scopedVars = scopedVars;
  13. target.format = target.format || 'time_series';
  14. target.timeColumn = target.timeColumn || 'time';
  15. target.metricColumn = target.metricColumn || 'none';
  16. target.group = target.group || [];
  17. target.where = target.where || [{ type: 'macro', name: '$__timeFilter', params: [] }];
  18. target.select = target.select || [[{ type: 'column', params: ['value'] }]];
  19. // handle pre query gui panels gracefully
  20. if (!('rawQuery' in this.target)) {
  21. if ('rawSql' in target) {
  22. // pre query gui panel
  23. target.rawQuery = true;
  24. } else {
  25. // new panel
  26. target.rawQuery = false;
  27. }
  28. }
  29. // give interpolateQueryStr access to this
  30. this.interpolateQueryStr = this.interpolateQueryStr.bind(this);
  31. }
  32. // remove identifier quoting from identifier to use in metadata queries
  33. unquoteIdentifier(value: string) {
  34. if (value[0] === '"' && value[value.length - 1] === '"') {
  35. return value.substring(1, value.length - 1).replace(/""/g, '"');
  36. } else {
  37. return value;
  38. }
  39. }
  40. quoteIdentifier(value: any) {
  41. return '"' + String(value).replace(/"/g, '""') + '"';
  42. }
  43. quoteLiteral(value: any) {
  44. return "'" + String(value).replace(/'/g, "''") + "'";
  45. }
  46. escapeLiteral(value: any) {
  47. return String(value).replace(/'/g, "''");
  48. }
  49. hasTimeGroup() {
  50. return find(this.target.group, (g: any) => g.type === 'time');
  51. }
  52. hasMetricColumn() {
  53. return this.target.metricColumn !== 'none';
  54. }
  55. interpolateQueryStr(value: any, variable: { multi: any; includeAll: any }, defaultFormatFn: any) {
  56. // if no multi or include all do not regexEscape
  57. if (!variable.multi && !variable.includeAll) {
  58. return this.escapeLiteral(value);
  59. }
  60. if (typeof value === 'string') {
  61. return this.quoteLiteral(value);
  62. }
  63. const escapedValues = map(value, this.quoteLiteral);
  64. return escapedValues.join(',');
  65. }
  66. render(interpolate?: any) {
  67. const target = this.target;
  68. // new query with no table set yet
  69. if (!this.target.rawQuery && !('table' in this.target)) {
  70. return '';
  71. }
  72. if (!target.rawQuery) {
  73. target.rawSql = this.buildQuery();
  74. }
  75. if (interpolate) {
  76. return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
  77. } else {
  78. return target.rawSql;
  79. }
  80. }
  81. hasUnixEpochTimecolumn() {
  82. return ['int4', 'int8', 'float4', 'float8', 'numeric'].indexOf(this.target.timeColumnType) > -1;
  83. }
  84. buildTimeColumn(alias = true) {
  85. const timeGroup = this.hasTimeGroup();
  86. let query;
  87. let macro = '$__timeGroup';
  88. if (timeGroup) {
  89. let args;
  90. if (timeGroup.params.length > 1 && timeGroup.params[1] !== 'none') {
  91. args = timeGroup.params.join(',');
  92. } else {
  93. args = timeGroup.params[0];
  94. }
  95. if (this.hasUnixEpochTimecolumn()) {
  96. macro = '$__unixEpochGroup';
  97. }
  98. if (alias) {
  99. macro += 'Alias';
  100. }
  101. query = macro + '(' + this.target.timeColumn + ',' + args + ')';
  102. } else {
  103. query = this.target.timeColumn;
  104. if (alias) {
  105. query += ' AS "time"';
  106. }
  107. }
  108. return query;
  109. }
  110. buildMetricColumn() {
  111. if (this.hasMetricColumn()) {
  112. return this.target.metricColumn + ' AS metric';
  113. }
  114. return '';
  115. }
  116. buildValueColumns() {
  117. let query = '';
  118. for (const column of this.target.select) {
  119. query += ',\n ' + this.buildValueColumn(column);
  120. }
  121. return query;
  122. }
  123. buildValueColumn(column: any) {
  124. let query = '';
  125. const columnName: any = find(column, (g: any) => g.type === 'column');
  126. query = columnName.params[0];
  127. const aggregate: any = find(column, (g: any) => g.type === 'aggregate' || g.type === 'percentile');
  128. const windows: any = find(column, (g: any) => g.type === 'window' || g.type === 'moving_window');
  129. if (aggregate) {
  130. const func = aggregate.params[0];
  131. switch (aggregate.type) {
  132. case 'aggregate':
  133. if (func === 'first' || func === 'last') {
  134. query = func + '(' + query + ',' + this.target.timeColumn + ')';
  135. } else {
  136. query = func + '(' + query + ')';
  137. }
  138. break;
  139. case 'percentile':
  140. query = func + '(' + aggregate.params[1] + ') WITHIN GROUP (ORDER BY ' + query + ')';
  141. break;
  142. }
  143. }
  144. if (windows) {
  145. const overParts = [];
  146. if (this.hasMetricColumn()) {
  147. overParts.push('PARTITION BY ' + this.target.metricColumn);
  148. }
  149. overParts.push('ORDER BY ' + this.buildTimeColumn(false));
  150. const over = overParts.join(' ');
  151. let curr: string;
  152. let prev: string;
  153. switch (windows.type) {
  154. case 'window':
  155. switch (windows.params[0]) {
  156. case 'delta':
  157. curr = query;
  158. prev = 'lag(' + curr + ') OVER (' + over + ')';
  159. query = curr + ' - ' + prev;
  160. break;
  161. case 'increase':
  162. curr = query;
  163. prev = 'lag(' + curr + ') OVER (' + over + ')';
  164. query = '(CASE WHEN ' + curr + ' >= ' + prev + ' THEN ' + curr + ' - ' + prev;
  165. query += ' WHEN ' + prev + ' IS NULL THEN NULL ELSE ' + curr + ' END)';
  166. break;
  167. case 'rate':
  168. let timeColumn = this.target.timeColumn;
  169. if (aggregate) {
  170. timeColumn = 'min(' + timeColumn + ')';
  171. }
  172. curr = query;
  173. prev = 'lag(' + curr + ') OVER (' + over + ')';
  174. query = '(CASE WHEN ' + curr + ' >= ' + prev + ' THEN ' + curr + ' - ' + prev;
  175. query += ' WHEN ' + prev + ' IS NULL THEN NULL ELSE ' + curr + ' END)';
  176. query += '/extract(epoch from ' + timeColumn + ' - lag(' + timeColumn + ') OVER (' + over + '))';
  177. break;
  178. default:
  179. query = windows.params[0] + '(' + query + ') OVER (' + over + ')';
  180. break;
  181. }
  182. break;
  183. case 'moving_window':
  184. query = windows.params[0] + '(' + query + ') OVER (' + over + ' ROWS ' + windows.params[1] + ' PRECEDING)';
  185. break;
  186. }
  187. }
  188. const alias: any = find(column, (g: any) => g.type === 'alias');
  189. if (alias) {
  190. query += ' AS ' + this.quoteIdentifier(alias.params[0]);
  191. }
  192. return query;
  193. }
  194. buildWhereClause() {
  195. let query = '';
  196. const conditions = map(this.target.where, (tag, index) => {
  197. switch (tag.type) {
  198. case 'macro':
  199. return tag.name + '(' + this.target.timeColumn + ')';
  200. break;
  201. case 'expression':
  202. return tag.params.join(' ');
  203. break;
  204. }
  205. });
  206. if (conditions.length > 0) {
  207. query = '\nWHERE\n ' + conditions.join(' AND\n ');
  208. }
  209. return query;
  210. }
  211. buildGroupClause() {
  212. let query = '';
  213. let groupSection = '';
  214. for (let i = 0; i < this.target.group.length; i++) {
  215. const part = this.target.group[i];
  216. if (i > 0) {
  217. groupSection += ', ';
  218. }
  219. if (part.type === 'time') {
  220. groupSection += '1';
  221. } else {
  222. groupSection += part.params[0];
  223. }
  224. }
  225. if (groupSection.length) {
  226. query = '\nGROUP BY ' + groupSection;
  227. if (this.hasMetricColumn()) {
  228. query += ',2';
  229. }
  230. }
  231. return query;
  232. }
  233. buildQuery() {
  234. let query = 'SELECT';
  235. query += '\n ' + this.buildTimeColumn();
  236. if (this.hasMetricColumn()) {
  237. query += ',\n ' + this.buildMetricColumn();
  238. }
  239. query += this.buildValueColumns();
  240. query += '\nFROM ' + this.target.table;
  241. query += this.buildWhereClause();
  242. query += this.buildGroupClause();
  243. query += '\nORDER BY 1';
  244. if (this.hasMetricColumn()) {
  245. query += ',2';
  246. }
  247. return query;
  248. }
  249. }