postgres_query.ts 7.6 KB

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