query_builder.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. define([
  2. 'lodash'
  3. ],
  4. function (_) {
  5. 'use strict';
  6. function InfluxQueryBuilder(target, database) {
  7. this.target = target;
  8. this.database = database;
  9. }
  10. function renderTagCondition (tag, index) {
  11. var str = "";
  12. var operator = tag.operator;
  13. var value = tag.value;
  14. if (index > 0) {
  15. str = (tag.condition || 'AND') + ' ';
  16. }
  17. if (!operator) {
  18. if (/^\/.*\/$/.test(tag.value)) {
  19. operator = '=~';
  20. } else {
  21. operator = '=';
  22. }
  23. }
  24. // quote value unless regex or number
  25. if (operator !== '=~' && operator !== '!~' && isNaN(+value)) {
  26. value = "'" + value + "'";
  27. }
  28. return str + '"' + tag.key + '" ' + operator + ' ' + value;
  29. }
  30. var p = InfluxQueryBuilder.prototype;
  31. p.build = function() {
  32. return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery();
  33. };
  34. p.buildExploreQuery = function(type, withKey, withMeasurementFilter) {
  35. var query;
  36. var measurement;
  37. if (type === 'TAG_KEYS') {
  38. query = 'SHOW TAG KEYS';
  39. measurement = this.target.measurement;
  40. } else if (type === 'TAG_VALUES') {
  41. query = 'SHOW TAG VALUES';
  42. measurement = this.target.measurement;
  43. } else if (type === 'MEASUREMENTS') {
  44. query = 'SHOW MEASUREMENTS';
  45. if (withMeasurementFilter)
  46. {
  47. query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';
  48. }
  49. } else if (type === 'FIELDS') {
  50. query = 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"';
  51. return query;
  52. } else if (type === 'RETENTION POLICIES') {
  53. query = 'SHOW RETENTION POLICIES on "' + this.database + '"';
  54. return query;
  55. }
  56. if (measurement) {
  57. if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) {
  58. measurement = '"' + measurement+ '"';
  59. }
  60. query += ' FROM ' + measurement;
  61. }
  62. if (withKey) {
  63. query += ' WITH KEY = "' + withKey + '"';
  64. }
  65. if (this.target.tags && this.target.tags.length > 0) {
  66. var whereConditions = _.reduce(this.target.tags, function(memo, tag) {
  67. // do not add a condition for the key we want to explore for
  68. if (tag.key === withKey) {
  69. return memo;
  70. }
  71. memo.push(renderTagCondition(tag, memo.length));
  72. return memo;
  73. }, []);
  74. if (whereConditions.length > 0) {
  75. query += ' WHERE ' + whereConditions.join(' ');
  76. }
  77. }
  78. return query;
  79. };
  80. return InfluxQueryBuilder;
  81. });