postgres_query.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 renderWhereConstraint(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 (interpolate) {
  119. value = this.templateSrv.replace(value, this.scopedVars);
  120. }
  121. return str + this.quoteIdentifier(tag.key) + ' ' + operator + ' ' + this.quoteLiteral(value);
  122. }
  123. interpolateQueryStr(value, variable, defaultFormatFn) {
  124. // if no multi or include all do not regexEscape
  125. if (!variable.multi && !variable.includeAll) {
  126. return value;
  127. }
  128. if (typeof value === 'string') {
  129. return kbn.regexEscape(value);
  130. }
  131. var escapedValues = _.map(value, kbn.regexEscape);
  132. return '(' + escapedValues.join('|') + ')';
  133. }
  134. render(interpolate?) {
  135. var target = this.target;
  136. if (target.rawQuery) {
  137. if (interpolate) {
  138. return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
  139. } else {
  140. return target.rawSql;
  141. }
  142. }
  143. var query = 'SELECT ';
  144. var timeGroup = this.hasGroupByTime();
  145. if (timeGroup) {
  146. var args;
  147. if (timeGroup.params.length > 1 && timeGroup.params[1] !== "none") {
  148. args = timeGroup.params.join(",");
  149. } else {
  150. args = timeGroup.params[0];
  151. }
  152. query += '$__timeGroup(' + this.quoteIdentifier(target.timeColumn) + ',' + args + '),';
  153. } else {
  154. query += this.quoteIdentifier(target.timeColumn) + ' AS time,';
  155. }
  156. var i, y;
  157. for (i = 0; i < this.selectModels.length; i++) {
  158. let parts = this.selectModels[i];
  159. var selectText = '';
  160. for (y = 0; y < parts.length; y++) {
  161. let part = parts[y];
  162. selectText = part.render(selectText);
  163. }
  164. if (i > 0) {
  165. query += ', ';
  166. }
  167. query += selectText;
  168. }
  169. if (this.target.metricColumn !== 'None') {
  170. query += "," + this.quoteIdentifier(this.target.metricColumn) + " AS metric";
  171. }
  172. query += ' FROM ' + this.quoteIdentifier(target.schema) + '.' + this.quoteIdentifier(target.table) + ' WHERE ';
  173. var conditions = _.map(target.where, (tag, index) => {
  174. return this.renderWhereConstraint(tag, index, interpolate);
  175. });
  176. if (conditions.length > 0) {
  177. query += '(' + conditions.join(' ') + ') AND ';
  178. }
  179. query += '$__timeFilter(' + this.quoteIdentifier(target.timeColumn) + ')';
  180. var groupBySection = '';
  181. for (i = 0; i < this.groupByParts.length; i++) {
  182. var part = this.groupByParts[i];
  183. if (i > 0) {
  184. groupBySection += ', ';
  185. }
  186. if (part.def.type === 'time') {
  187. groupBySection += '1';
  188. } else {
  189. groupBySection += part.render('');
  190. }
  191. }
  192. if (groupBySection.length) {
  193. query += ' GROUP BY ' + groupBySection;
  194. }
  195. query += ' ORDER BY 1';
  196. this.target.rawSql = query;
  197. if (interpolate) {
  198. query = this.templateSrv.replace(query, this.scopedVars, this.interpolateQueryStr);
  199. }
  200. return query;
  201. }
  202. renderAdhocFilters(filters) {
  203. var conditions = _.map(filters, (tag, index) => {
  204. return this.renderWhereConstraint(tag, index, false);
  205. });
  206. return conditions.join(' ');
  207. }
  208. }