postgres_query.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. // handle pre query gui panels gracefully
  24. if (!('rawQuery' in this.target)) {
  25. if ('rawSql' in target) {
  26. // pre query gui panel
  27. target.rawQuery = true;
  28. } else {
  29. // new panel
  30. target.rawQuery = false;
  31. }
  32. }
  33. // give interpolateQueryStr access to this
  34. this.interpolateQueryStr = this.interpolateQueryStr.bind(this);
  35. this.updateProjection();
  36. }
  37. // remove identifier quoting from identifier to use in metadata queries
  38. unquoteIdentifier(value) {
  39. if (value[0] === '"' && value[value.length - 1] === '"') {
  40. return value.substring(1, value.length - 1).replace('""', '"');
  41. } else {
  42. return value;
  43. }
  44. }
  45. quoteIdentifier(value) {
  46. return '"' + value.replace('"', '""') + '"';
  47. }
  48. quoteLiteral(value) {
  49. return "'" + value.replace("'", "''") + "'";
  50. }
  51. updateProjection() {
  52. this.selectModels = _.map(this.target.select, function(parts: any) {
  53. return _.map(parts, sqlPart.create).filter(n => n);
  54. });
  55. this.whereParts = _.map(this.target.where, sqlPart.create).filter(n => n);
  56. this.groupByParts = _.map(this.target.groupBy, sqlPart.create).filter(n => n);
  57. }
  58. updatePersistedParts() {
  59. this.target.select = _.map(this.selectModels, function(selectParts) {
  60. return _.map(selectParts, function(part: any) {
  61. return { type: part.def.type, params: part.params };
  62. });
  63. });
  64. this.target.where = _.map(this.whereParts, function(part: any) {
  65. return { type: part.def.type, name: part.name, params: part.params };
  66. });
  67. this.target.groupBy = _.map(this.groupByParts, function(part: any) {
  68. return { type: part.def.type, params: part.params };
  69. });
  70. }
  71. hasGroupByTime() {
  72. return _.find(this.target.groupBy, (g: any) => g.type === 'time');
  73. }
  74. addGroupBy(partType, value) {
  75. var partModel = sqlPart.create({ type: partType, params: [value] });
  76. var partCount = this.target.groupBy.length;
  77. if (partCount === 0) {
  78. this.target.groupBy.push(partModel.part);
  79. } else if (partType === 'time') {
  80. // put timeGroup at start
  81. this.target.groupBy.splice(0, 0, partModel.part);
  82. } else {
  83. this.target.groupBy.push(partModel.part);
  84. }
  85. if (partType === 'time') {
  86. partModel.part.params = ['1m', 'none'];
  87. }
  88. // add aggregates when adding group by
  89. for (let i = 0; i < this.target.select.length; i++) {
  90. var selectParts = this.target.select[i];
  91. if (!selectParts.some(part => part.type === 'aggregate')) {
  92. selectParts.splice(1, 0, { type: 'aggregate', params: ['avg'] });
  93. if (!selectParts.some(part => part.type === 'alias')) {
  94. selectParts.push({ type: 'alias', params: [selectParts[0].params[0]] });
  95. }
  96. }
  97. }
  98. this.updateProjection();
  99. }
  100. removeGroupByPart(part, index) {
  101. if (part.def.type === 'time') {
  102. // remove aggregations
  103. this.target.select = _.map(this.target.select, (s: any) => {
  104. return _.filter(s, (part: any) => {
  105. if (part.type === 'aggregate') {
  106. return false;
  107. }
  108. return true;
  109. });
  110. });
  111. }
  112. this.target.groupBy.splice(index, 1);
  113. this.updateProjection();
  114. }
  115. removeSelectPart(selectParts, part) {
  116. // if we remove the field remove the whole statement
  117. if (part.def.type === 'column') {
  118. if (this.selectModels.length > 1) {
  119. var modelsIndex = _.indexOf(this.selectModels, selectParts);
  120. this.selectModels.splice(modelsIndex, 1);
  121. }
  122. } else {
  123. var partIndex = _.indexOf(selectParts, part);
  124. selectParts.splice(partIndex, 1);
  125. }
  126. this.updatePersistedParts();
  127. }
  128. addSelectPart(selectParts, type) {
  129. var partModel = sqlPart.create({ type: type });
  130. partModel.def.addStrategy(selectParts, partModel, this);
  131. this.updatePersistedParts();
  132. }
  133. interpolateQueryStr(value, variable, defaultFormatFn) {
  134. // if no multi or include all do not regexEscape
  135. if (!variable.multi && !variable.includeAll) {
  136. return value;
  137. }
  138. if (typeof value === 'string') {
  139. return this.quoteLiteral(value);
  140. }
  141. var escapedValues = _.map(value, this.quoteLiteral);
  142. return '(' + escapedValues.join(',') + ')';
  143. }
  144. render(interpolate?) {
  145. let target = this.target;
  146. let query;
  147. if (target.rawQuery) {
  148. if (interpolate) {
  149. return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
  150. } else {
  151. return target.rawSql;
  152. }
  153. }
  154. query = this.buildQuery(target);
  155. if (interpolate) {
  156. query = this.templateSrv.replace(query, this.scopedVars, this.interpolateQueryStr);
  157. }
  158. return query;
  159. }
  160. buildTimeColumn(target) {
  161. let timeGroup = this.hasGroupByTime();
  162. let query;
  163. if (timeGroup) {
  164. var args;
  165. if (timeGroup.params.length > 1 && timeGroup.params[1] !== 'none') {
  166. args = timeGroup.params.join(',');
  167. } else {
  168. args = timeGroup.params[0];
  169. }
  170. query = '$__timeGroup(' + target.timeColumn + ',' + args + ')';
  171. } else {
  172. query = target.timeColumn + ' AS "time"';
  173. }
  174. return query;
  175. }
  176. buildValueColumns(target) {
  177. let query = '';
  178. for (let i = 0; i < this.selectModels.length; i++) {
  179. let parts = this.selectModels[i];
  180. var selectText = '';
  181. for (let y = 0; y < parts.length; y++) {
  182. let part = parts[y];
  183. selectText = part.render(selectText);
  184. }
  185. query += ', ' + selectText;
  186. }
  187. return query;
  188. }
  189. buildWhereClause(target) {
  190. let query = '';
  191. var conditions = _.map(target.where, (tag, index) => {
  192. switch (tag.type) {
  193. case 'macro':
  194. return tag.name + '(' + target.timeColumn + ')';
  195. break;
  196. case 'expression':
  197. return tag.params.join(' ');
  198. break;
  199. }
  200. });
  201. if (conditions.length > 0) {
  202. query = ' WHERE ' + conditions.join(' AND ');
  203. }
  204. return query;
  205. }
  206. buildGroupByClause(target) {
  207. let query = '';
  208. let groupBySection = '';
  209. for (let i = 0; i < this.groupByParts.length; i++) {
  210. var part = this.groupByParts[i];
  211. if (i > 0) {
  212. groupBySection += ', ';
  213. }
  214. if (part.def.type === 'time') {
  215. groupBySection += '1';
  216. } else {
  217. groupBySection += part.render('');
  218. }
  219. }
  220. if (groupBySection.length) {
  221. query = ' GROUP BY ' + groupBySection;
  222. if (this.target.metricColumn !== 'None') {
  223. query += ',2';
  224. }
  225. }
  226. return query;
  227. }
  228. buildQuery(target) {
  229. let query = 'SELECT ';
  230. query += this.buildTimeColumn(target);
  231. if (this.target.metricColumn !== 'None') {
  232. query += ',' + this.target.metricColumn + ' AS metric';
  233. }
  234. query += this.buildValueColumns(target);
  235. query += ' FROM ' + target.schema + '.' + target.table;
  236. query += this.buildWhereClause(target);
  237. query += this.buildGroupByClause(target);
  238. query += ' ORDER BY 1';
  239. this.target.rawSql = query;
  240. return query;
  241. }
  242. }