mysql_query.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import _ from 'lodash';
  2. export default class MysqlQuery {
  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 ['int', 'bigint', 'double'].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 + ' ELSE ' + curr + ' END)';
  158. break;
  159. case 'rate':
  160. let timeColumn = this.target.timeColumn;
  161. if (aggregate) {
  162. timeColumn = 'min(' + timeColumn + ')';
  163. }
  164. curr = query;
  165. prev = 'lag(' + curr + ') OVER (' + over + ')';
  166. query = '(CASE WHEN ' + curr + ' >= ' + prev + ' THEN ' + curr + ' - ' + prev + ' ELSE ' + curr + ' END)';
  167. query += '/extract(epoch from ' + timeColumn + ' - lag(' + timeColumn + ') OVER (' + over + '))';
  168. break;
  169. default:
  170. query = windows.params[0] + '(' + query + ') OVER (' + over + ')';
  171. break;
  172. }
  173. break;
  174. case 'moving_window':
  175. query = windows.params[0] + '(' + query + ') OVER (' + over + ' ROWS ' + windows.params[1] + ' PRECEDING)';
  176. break;
  177. }
  178. }
  179. const alias = _.find(column, (g: any) => g.type === 'alias');
  180. if (alias) {
  181. query += ' AS ' + this.quoteIdentifier(alias.params[0]);
  182. }
  183. return query;
  184. }
  185. buildWhereClause() {
  186. let query = '';
  187. const conditions = _.map(this.target.where, (tag, index) => {
  188. switch (tag.type) {
  189. case 'macro':
  190. return tag.name + '(' + this.target.timeColumn + ')';
  191. break;
  192. case 'expression':
  193. return tag.params.join(' ');
  194. break;
  195. }
  196. });
  197. if (conditions.length > 0) {
  198. query = '\nWHERE\n ' + conditions.join(' AND\n ');
  199. }
  200. return query;
  201. }
  202. buildGroupClause() {
  203. let query = '';
  204. let groupSection = '';
  205. for (let i = 0; i < this.target.group.length; i++) {
  206. const part = this.target.group[i];
  207. if (i > 0) {
  208. groupSection += ', ';
  209. }
  210. if (part.type === 'time') {
  211. groupSection += '1';
  212. } else {
  213. groupSection += part.params[0];
  214. }
  215. }
  216. if (groupSection.length) {
  217. query = '\nGROUP BY ' + groupSection;
  218. if (this.hasMetricColumn()) {
  219. query += ',2';
  220. }
  221. }
  222. return query;
  223. }
  224. buildQuery() {
  225. let query = 'SELECT';
  226. query += '\n ' + this.buildTimeColumn();
  227. if (this.hasMetricColumn()) {
  228. query += ',\n ' + this.buildMetricColumn();
  229. }
  230. query += this.buildValueColumns();
  231. query += '\nFROM ' + this.target.table;
  232. query += this.buildWhereClause();
  233. query += this.buildGroupClause();
  234. query += '\nORDER BY 1';
  235. return query;
  236. }
  237. }