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