postgres_query.ts 6.1 KB

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