postgres_query.ts 6.7 KB

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