postgres_query.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. removeSelectPart(selectParts, part) {
  96. // if we remove the field remove the whole statement
  97. if (part.def.type === 'column') {
  98. if (this.selectModels.length > 1) {
  99. var modelsIndex = _.indexOf(this.selectModels, selectParts);
  100. this.selectModels.splice(modelsIndex, 1);
  101. }
  102. } else {
  103. var partIndex = _.indexOf(selectParts, part);
  104. selectParts.splice(partIndex, 1);
  105. }
  106. this.updatePersistedParts();
  107. }
  108. addSelectPart(selectParts, type) {
  109. var partModel = sqlPart.create({ type: type });
  110. partModel.def.addStrategy(selectParts, partModel, this);
  111. this.updatePersistedParts();
  112. }
  113. interpolateQueryStr(value, variable, defaultFormatFn) {
  114. // if no multi or include all do not regexEscape
  115. if (!variable.multi && !variable.includeAll) {
  116. return value;
  117. }
  118. if (typeof value === 'string') {
  119. return this.quoteLiteral(value);
  120. }
  121. var escapedValues = _.map(value, this.quoteLiteral);
  122. return '(' + escapedValues.join(',') + ')';
  123. }
  124. render(interpolate?) {
  125. var target = this.target;
  126. if (target.rawQuery) {
  127. if (interpolate) {
  128. return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
  129. } else {
  130. return target.rawSql;
  131. }
  132. }
  133. var query = 'SELECT ';
  134. var timeGroup = this.hasGroupByTime();
  135. if (timeGroup) {
  136. var args;
  137. if (timeGroup.params.length > 1 && timeGroup.params[1] !== 'none') {
  138. args = timeGroup.params.join(',');
  139. } else {
  140. args = timeGroup.params[0];
  141. }
  142. query += '$__timeGroup(' + target.timeColumn + ',' + args + ')';
  143. } else {
  144. query += target.timeColumn + ' AS "time"';
  145. }
  146. if (this.target.metricColumn !== 'None') {
  147. query += ',' + this.target.metricColumn + ' AS metric';
  148. }
  149. var i, y;
  150. for (i = 0; i < this.selectModels.length; i++) {
  151. let parts = this.selectModels[i];
  152. var selectText = '';
  153. for (y = 0; y < parts.length; y++) {
  154. let part = parts[y];
  155. selectText = part.render(selectText);
  156. }
  157. query += ', ' + selectText;
  158. }
  159. query += ' FROM ' + target.schema + '.' + target.table;
  160. var conditions = _.map(target.where, (tag, index) => {
  161. switch (tag.type) {
  162. case 'macro':
  163. return tag.name + '(' + target.timeColumn + ')';
  164. break;
  165. case 'expression':
  166. return tag.params.join(' ');
  167. break;
  168. }
  169. });
  170. if (conditions.length > 0) {
  171. query += ' WHERE ' + conditions.join(' AND ');
  172. }
  173. var groupBySection = '';
  174. for (i = 0; i < this.groupByParts.length; i++) {
  175. var part = this.groupByParts[i];
  176. if (i > 0) {
  177. groupBySection += ', ';
  178. }
  179. if (part.def.type === 'time') {
  180. groupBySection += '1';
  181. } else {
  182. groupBySection += part.render('');
  183. }
  184. }
  185. if (groupBySection.length) {
  186. query += ' GROUP BY ' + groupBySection;
  187. if (this.target.metricColumn !== 'None') {
  188. query += ',2';
  189. }
  190. }
  191. query += ' ORDER BY 1';
  192. this.target.rawSql = query;
  193. if (interpolate) {
  194. query = this.templateSrv.replace(query, this.scopedVars, this.interpolateQueryStr);
  195. }
  196. return query;
  197. }
  198. }