postgres_query.ts 7.1 KB

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