postgres_query.ts 6.2 KB

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