postgres_query.ts 6.5 KB

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