postgres_query.ts 6.8 KB

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