postgres_query.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import _ from 'lodash';
  2. import queryPart from './query_part';
  3. import kbn from 'app/core/utils/kbn';
  4. export default class PostgresQuery {
  5. target: any;
  6. selectModels: any[];
  7. queryBuilder: any;
  8. groupByParts: any;
  9. templateSrv: any;
  10. scopedVars: any;
  11. /** @ngInject */
  12. constructor(target, templateSrv?, scopedVars?) {
  13. this.target = target;
  14. this.templateSrv = templateSrv;
  15. this.scopedVars = scopedVars;
  16. target.schema = target.schema || 'public';
  17. target.format = target.format || 'time_series';
  18. target.timeColumn = target.timeColumn || 'time';
  19. target.metricColumn = target.metricColumn || 'None';
  20. target.orderByTime = target.orderByTime || 'ASC';
  21. target.groupBy = target.groupBy || [];
  22. target.where = target.where || [];
  23. target.select = target.select || [[{ type: 'column', params: ['value'] }]];
  24. this.updateProjection();
  25. }
  26. quoteIdentifier(value) {
  27. return '"' + value + '"';
  28. }
  29. quoteLiteral(value) {
  30. return "'" + value + "'";
  31. }
  32. updateProjection() {
  33. this.selectModels = _.map(this.target.select, function(parts: any) {
  34. return _.map(parts, queryPart.create);
  35. });
  36. this.groupByParts = _.map(this.target.groupBy, queryPart.create);
  37. }
  38. updatePersistedParts() {
  39. this.target.select = _.map(this.selectModels, function(selectParts) {
  40. return _.map(selectParts, function(part: any) {
  41. return { type: part.def.type, params: part.params };
  42. });
  43. });
  44. }
  45. hasGroupByTime() {
  46. return _.find(this.target.groupBy, (g: any) => g.type === 'time');
  47. }
  48. hasFill() {
  49. return _.find(this.target.groupBy, (g: any) => g.type === 'fill');
  50. }
  51. addGroupBy(value) {
  52. var stringParts = value.match(/^(\w+)(\((.*)\))?$/);
  53. var typePart = stringParts[1];
  54. var args = stringParts[3].split(",");
  55. var partModel = queryPart.create({ type: typePart, params: args });
  56. var partCount = this.target.groupBy.length;
  57. if (partCount === 0) {
  58. this.target.groupBy.push(partModel.part);
  59. } else if (typePart === 'time') {
  60. this.target.groupBy.splice(0, 0, partModel.part);
  61. } else if (typePart === 'column') {
  62. if (this.target.groupBy[partCount - 1].type === 'fill') {
  63. this.target.groupBy.splice(partCount - 1, 0, partModel.part);
  64. } else {
  65. this.target.groupBy.push(partModel.part);
  66. }
  67. } else {
  68. this.target.groupBy.push(partModel.part);
  69. }
  70. this.updateProjection();
  71. }
  72. removeGroupByPart(part, index) {
  73. var categories = queryPart.getCategories();
  74. if (part.def.type === 'time') {
  75. // remove aggregations
  76. this.target.select = _.map(this.target.select, (s: any) => {
  77. return _.filter(s, (part: any) => {
  78. var partModel = queryPart.create(part);
  79. if (partModel.def.category === categories.Aggregations) {
  80. return false;
  81. }
  82. return true;
  83. });
  84. });
  85. }
  86. this.target.groupBy.splice(index, 1);
  87. this.updateProjection();
  88. }
  89. removeSelect(index: number) {
  90. this.target.select.splice(index, 1);
  91. this.updateProjection();
  92. }
  93. removeSelectPart(selectParts, part) {
  94. // if we remove the field remove the whole statement
  95. if (part.def.type === 'column') {
  96. if (this.selectModels.length > 1) {
  97. var modelsIndex = _.indexOf(this.selectModels, selectParts);
  98. this.selectModels.splice(modelsIndex, 1);
  99. }
  100. } else {
  101. var partIndex = _.indexOf(selectParts, part);
  102. selectParts.splice(partIndex, 1);
  103. }
  104. this.updatePersistedParts();
  105. }
  106. addSelectPart(selectParts, type) {
  107. var partModel = queryPart.create({ type: type });
  108. partModel.def.addStrategy(selectParts, partModel, this);
  109. this.updatePersistedParts();
  110. }
  111. private renderTagCondition(tag, index, interpolate) {
  112. var str = '';
  113. var operator = tag.operator;
  114. var value = tag.value;
  115. if (index > 0) {
  116. str = (tag.condition || 'AND') + ' ';
  117. }
  118. if (!operator) {
  119. if (/^\/.*\/$/.test(value)) {
  120. operator = '=~';
  121. } else {
  122. operator = '=';
  123. }
  124. }
  125. // quote value unless regex
  126. if (operator !== '=~' && operator !== '!~') {
  127. if (interpolate) {
  128. value = this.templateSrv.replace(value, this.scopedVars);
  129. }
  130. if (operator !== '>' && operator !== '<') {
  131. value = "'" + value.replace(/\\/g, '\\\\') + "'";
  132. }
  133. } else if (interpolate) {
  134. value = this.templateSrv.replace(value, this.scopedVars, 'regex');
  135. }
  136. return str + '"' + tag.key + '" ' + operator + ' ' + value;
  137. }
  138. interpolateQueryStr(value, variable, defaultFormatFn) {
  139. // if no multi or include all do not regexEscape
  140. if (!variable.multi && !variable.includeAll) {
  141. return value;
  142. }
  143. if (typeof value === 'string') {
  144. return kbn.regexEscape(value);
  145. }
  146. var escapedValues = _.map(value, kbn.regexEscape);
  147. return '(' + escapedValues.join('|') + ')';
  148. }
  149. render(interpolate?) {
  150. var target = this.target;
  151. if (target.rawQuery) {
  152. if (interpolate) {
  153. return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
  154. } else {
  155. return target.rawSql;
  156. }
  157. }
  158. var query = 'SELECT ';
  159. var timeGroup = this.hasGroupByTime();
  160. if (timeGroup) {
  161. var args;
  162. if (timeGroup.params.length > 1 && timeGroup.params[1] !== "none") {
  163. args = timeGroup.params.join(",");
  164. } else {
  165. args = timeGroup.params[0];
  166. }
  167. query += '$__timeGroup(' + this.quoteIdentifier(target.timeColumn) + ',' + args + '),';
  168. } else {
  169. query += this.quoteIdentifier(target.timeColumn) + ' AS time,';
  170. }
  171. var i, y;
  172. for (i = 0; i < this.selectModels.length; i++) {
  173. let parts = this.selectModels[i];
  174. var selectText = '';
  175. for (y = 0; y < parts.length; y++) {
  176. let part = parts[y];
  177. selectText = part.render(selectText);
  178. }
  179. if (i > 0) {
  180. query += ', ';
  181. }
  182. query += selectText;
  183. }
  184. if (this.target.metricColumn !== 'None') {
  185. query += "," + this.quoteIdentifier(this.target.metricColumn) + " AS metric";
  186. }
  187. query += ' FROM ' + target.schema + '.' + target.table + ' WHERE ';
  188. var conditions = _.map(target.where, (tag, index) => {
  189. return this.renderTagCondition(tag, index, interpolate);
  190. });
  191. if (conditions.length > 0) {
  192. query += '(' + conditions.join(' ') + ') AND ';
  193. }
  194. query += '$__timeFilter(' + this.quoteIdentifier(target.timeColumn) + ')';
  195. var groupBySection = '';
  196. for (i = 0; i < this.groupByParts.length; i++) {
  197. var part = this.groupByParts[i];
  198. if (i > 0) {
  199. groupBySection += ', ';
  200. }
  201. if (part.def.type === 'time') {
  202. groupBySection += '1';
  203. } else {
  204. groupBySection += part.render('');
  205. }
  206. }
  207. if (groupBySection.length) {
  208. query += ' GROUP BY ' + groupBySection;
  209. }
  210. query += ' ORDER BY 1';
  211. this.target.rawSql = query;
  212. if (interpolate) {
  213. query = this.templateSrv.replace(query, this.scopedVars, this.interpolateQueryStr);
  214. }
  215. return query;
  216. }
  217. renderAdhocFilters(filters) {
  218. var conditions = _.map(filters, (tag, index) => {
  219. return this.renderTagCondition(tag, index, false);
  220. });
  221. return conditions.join(' ');
  222. }
  223. }