postgres_query.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. 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. if (part.type === "aggregate") {
  75. return false;
  76. }
  77. return true;
  78. });
  79. });
  80. }
  81. this.target.groupBy.splice(index, 1);
  82. this.updateProjection();
  83. }
  84. removeSelect(index: number) {
  85. this.target.select.splice(index, 1);
  86. this.updateProjection();
  87. }
  88. removeSelectPart(selectParts, part) {
  89. // if we remove the field remove the whole statement
  90. if (part.def.type === 'column') {
  91. if (this.selectModels.length > 1) {
  92. var modelsIndex = _.indexOf(this.selectModels, selectParts);
  93. this.selectModels.splice(modelsIndex, 1);
  94. }
  95. } else {
  96. var partIndex = _.indexOf(selectParts, part);
  97. selectParts.splice(partIndex, 1);
  98. }
  99. this.updatePersistedParts();
  100. }
  101. addSelectPart(selectParts, type) {
  102. var partModel = queryPart.create({ type: type });
  103. partModel.def.addStrategy(selectParts, partModel, this);
  104. this.updatePersistedParts();
  105. }
  106. private renderWhereConstraint(constraint, index, interpolate) {
  107. var str = '';
  108. var operator = constraint.operator;
  109. var value = constraint.value;
  110. if (index > 0) {
  111. str = (constraint.condition || 'AND') + ' ';
  112. }
  113. if (interpolate) {
  114. value = this.templateSrv.replace(value, this.scopedVars);
  115. }
  116. return str + constraint.key + ' ' + operator + ' ' + value;
  117. }
  118. interpolateQueryStr(value, variable, defaultFormatFn) {
  119. // if no multi or include all do not regexEscape
  120. if (!variable.multi && !variable.includeAll) {
  121. return value;
  122. }
  123. if (typeof value === 'string') {
  124. return this.quoteLiteral(value);
  125. }
  126. var escapedValues = _.map(value, this.quoteLiteral);
  127. return '(' + escapedValues.join(',') + ')';
  128. }
  129. render(interpolate?) {
  130. var target = this.target;
  131. if (target.rawQuery) {
  132. if (interpolate) {
  133. return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
  134. } else {
  135. return target.rawSql;
  136. }
  137. }
  138. var query = 'SELECT ';
  139. var timeGroup = this.hasGroupByTime();
  140. if (timeGroup) {
  141. var args;
  142. if (timeGroup.params.length > 1 && timeGroup.params[1] !== "none") {
  143. args = timeGroup.params.join(",");
  144. } else {
  145. args = timeGroup.params[0];
  146. }
  147. query += '$__timeGroup(' + this.quoteIdentifier(target.timeColumn) + ',' + args + '),';
  148. } else {
  149. query += this.quoteIdentifier(target.timeColumn) + ' AS time,';
  150. }
  151. var i, y;
  152. for (i = 0; i < this.selectModels.length; i++) {
  153. let parts = this.selectModels[i];
  154. var selectText = '';
  155. for (y = 0; y < parts.length; y++) {
  156. let part = parts[y];
  157. selectText = part.render(selectText);
  158. }
  159. if (i > 0) {
  160. query += ', ';
  161. }
  162. query += selectText;
  163. }
  164. if (this.target.metricColumn !== 'None') {
  165. query += "," + this.quoteIdentifier(this.target.metricColumn) + " AS metric";
  166. }
  167. query += ' FROM ' + this.quoteIdentifier(target.schema) + '.' + this.quoteIdentifier(target.table) + ' WHERE ';
  168. var conditions = _.map(target.where, (tag, index) => {
  169. return this.renderWhereConstraint(tag, index, false);
  170. });
  171. if (conditions.length > 0) {
  172. query += '(' + conditions.join(' ') + ') AND ';
  173. }
  174. query += '$__timeFilter(' + this.quoteIdentifier(target.timeColumn) + ')';
  175. var groupBySection = '';
  176. for (i = 0; i < this.groupByParts.length; i++) {
  177. var part = this.groupByParts[i];
  178. if (i > 0) {
  179. groupBySection += ', ';
  180. }
  181. if (part.def.type === 'time') {
  182. groupBySection += '1';
  183. } else {
  184. groupBySection += part.render('');
  185. }
  186. }
  187. if (groupBySection.length) {
  188. query += ' GROUP BY ' + groupBySection;
  189. }
  190. query += ' ORDER BY 1';
  191. this.target.rawSql = query;
  192. if (interpolate) {
  193. query = this.templateSrv.replace(query, this.scopedVars, this.interpolateQueryStr);
  194. }
  195. return query;
  196. }
  197. renderAdhocFilters(filters) {
  198. var conditions = _.map(filters, (tag, index) => {
  199. return this.renderWhereConstraint(tag, index, false);
  200. });
  201. return conditions.join(' ');
  202. }
  203. }