postgres_query.ts 6.9 KB

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