postgres_query.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import _ from 'lodash';
  2. import sqlPart from './sql_part';
  3. export default class PostgresQuery {
  4. target: any;
  5. selectModels: any[];
  6. queryBuilder: any;
  7. groupByParts: any[];
  8. whereParts: 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. // handle pre query gui panels gracefully
  24. if (!('rawQuery' in this.target)) {
  25. target.rawQuery = true;
  26. }
  27. // give interpolateQueryStr access to this
  28. this.interpolateQueryStr = this.interpolateQueryStr.bind(this);
  29. this.updateProjection();
  30. }
  31. // remove identifier quoting from identifier to use in metadata queries
  32. unquoteIdentifier(value) {
  33. if (value[0] === '"' && value[value.length - 1] === '"') {
  34. return value.substring(1, value.length - 1).replace('""', '"');
  35. } else {
  36. return value;
  37. }
  38. }
  39. quoteIdentifier(value) {
  40. return '"' + value.replace('"', '""') + '"';
  41. }
  42. quoteLiteral(value) {
  43. return "'" + value.replace("'", "''") + "'";
  44. }
  45. updateProjection() {
  46. this.selectModels = _.map(this.target.select, function(parts: any) {
  47. return _.map(parts, sqlPart.create);
  48. });
  49. this.whereParts = _.map(this.target.where, sqlPart.create);
  50. this.groupByParts = _.map(this.target.groupBy, sqlPart.create);
  51. }
  52. updatePersistedParts() {
  53. this.target.select = _.map(this.selectModels, function(selectParts) {
  54. return _.map(selectParts, function(part: any) {
  55. return { type: part.def.type, params: part.params };
  56. });
  57. });
  58. this.target.where = _.map(this.whereParts, function(part: any) {
  59. return { type: part.def.type, name: part.name, params: part.params };
  60. });
  61. this.target.groupBy = _.map(this.groupByParts, function(part: any) {
  62. return { type: part.def.type, params: part.params };
  63. });
  64. }
  65. hasGroupByTime() {
  66. return _.find(this.target.groupBy, (g: any) => g.type === 'time');
  67. }
  68. addGroupBy(partType, value) {
  69. var partModel = sqlPart.create({ type: partType, params: [value] });
  70. var partCount = this.target.groupBy.length;
  71. if (partCount === 0) {
  72. this.target.groupBy.push(partModel.part);
  73. } else if (partType === 'time') {
  74. // put timeGroup at start
  75. this.target.groupBy.splice(0, 0, partModel.part);
  76. } else {
  77. this.target.groupBy.push(partModel.part);
  78. }
  79. if (partType === 'time') {
  80. partModel.part.params = ['1m', 'none'];
  81. }
  82. // add aggregates when adding group by
  83. for (let i = 0; i < this.target.select.length; i++) {
  84. var selectParts = this.target.select[i];
  85. if (!selectParts.some(part => part.type === 'aggregate')) {
  86. selectParts.splice(1, 0, { type: 'aggregate', params: ['avg'] });
  87. }
  88. }
  89. this.updateProjection();
  90. }
  91. removeGroupByPart(part, index) {
  92. if (part.def.type === 'time') {
  93. // remove aggregations
  94. this.target.select = _.map(this.target.select, (s: any) => {
  95. return _.filter(s, (part: any) => {
  96. if (part.type === 'aggregate') {
  97. return false;
  98. }
  99. return true;
  100. });
  101. });
  102. }
  103. this.target.groupBy.splice(index, 1);
  104. this.updateProjection();
  105. }
  106. removeSelectPart(selectParts, part) {
  107. // if we remove the field remove the whole statement
  108. if (part.def.type === 'column') {
  109. if (this.selectModels.length > 1) {
  110. var modelsIndex = _.indexOf(this.selectModels, selectParts);
  111. this.selectModels.splice(modelsIndex, 1);
  112. }
  113. } else {
  114. var partIndex = _.indexOf(selectParts, part);
  115. selectParts.splice(partIndex, 1);
  116. }
  117. this.updatePersistedParts();
  118. }
  119. addSelectPart(selectParts, type) {
  120. var partModel = sqlPart.create({ type: type });
  121. partModel.def.addStrategy(selectParts, partModel, this);
  122. this.updatePersistedParts();
  123. }
  124. interpolateQueryStr(value, variable, defaultFormatFn) {
  125. // if no multi or include all do not regexEscape
  126. if (!variable.multi && !variable.includeAll) {
  127. return value;
  128. }
  129. if (typeof value === 'string') {
  130. return this.quoteLiteral(value);
  131. }
  132. var escapedValues = _.map(value, this.quoteLiteral);
  133. return '(' + escapedValues.join(',') + ')';
  134. }
  135. render(interpolate?) {
  136. var target = this.target;
  137. if (target.rawQuery) {
  138. if (interpolate) {
  139. return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
  140. } else {
  141. return target.rawSql;
  142. }
  143. }
  144. var query = 'SELECT ';
  145. var timeGroup = this.hasGroupByTime();
  146. if (timeGroup) {
  147. var args;
  148. if (timeGroup.params.length > 1 && timeGroup.params[1] !== 'none') {
  149. args = timeGroup.params.join(',');
  150. } else {
  151. args = timeGroup.params[0];
  152. }
  153. query += '$__timeGroup(' + target.timeColumn + ',' + args + ')';
  154. } else {
  155. query += target.timeColumn + ' AS "time"';
  156. }
  157. if (this.target.metricColumn !== 'None') {
  158. query += ',' + this.target.metricColumn + ' AS metric';
  159. }
  160. var i, y;
  161. for (i = 0; i < this.selectModels.length; i++) {
  162. let parts = this.selectModels[i];
  163. var selectText = '';
  164. for (y = 0; y < parts.length; y++) {
  165. let part = parts[y];
  166. selectText = part.render(selectText);
  167. }
  168. query += ', ' + selectText;
  169. }
  170. query += ' FROM ' + target.schema + '.' + target.table;
  171. var conditions = _.map(target.where, (tag, index) => {
  172. switch (tag.type) {
  173. case 'macro':
  174. return tag.name + '(' + target.timeColumn + ')';
  175. break;
  176. case 'expression':
  177. return tag.params.join(' ');
  178. break;
  179. }
  180. });
  181. if (conditions.length > 0) {
  182. query += ' WHERE ' + conditions.join(' AND ');
  183. }
  184. var groupBySection = '';
  185. for (i = 0; i < this.groupByParts.length; i++) {
  186. var part = this.groupByParts[i];
  187. if (i > 0) {
  188. groupBySection += ', ';
  189. }
  190. if (part.def.type === 'time') {
  191. groupBySection += '1';
  192. } else {
  193. groupBySection += part.render('');
  194. }
  195. }
  196. if (groupBySection.length) {
  197. query += ' GROUP BY ' + groupBySection;
  198. if (this.target.metricColumn !== 'None') {
  199. query += ',2';
  200. }
  201. }
  202. query += ' ORDER BY 1';
  203. this.target.rawSql = query;
  204. if (interpolate) {
  205. query = this.templateSrv.replace(query, this.scopedVars, this.interpolateQueryStr);
  206. }
  207. return query;
  208. }
  209. }