postgres_query.ts 6.4 KB

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