Explorar o código

feat(influxdb): more work on changing the influxdb editor to support better aliasing and interval options, #2647, #2599

Torkel Ödegaard %!s(int64=10) %!d(string=hai) anos
pai
achega
c4c3f9dc1f

+ 0 - 1
public/app/plugins/datasource/influxdb/datasource.js

@@ -6,7 +6,6 @@ define([
   './queryBuilder',
   './directives',
   './queryCtrl',
-  './funcEditor',
 ],
 function (angular, _, kbn, InfluxSeries, InfluxQueryBuilder) {
   'use strict';

+ 0 - 152
public/app/plugins/datasource/influxdb/funcEditor.js

@@ -1,152 +0,0 @@
-define([
-  'angular',
-  'lodash',
-  'jquery',
-],
-function (angular, _, $) {
-  'use strict';
-
-  angular
-    .module('grafana.directives')
-    .directive('influxdbFuncEditor', function($compile) {
-
-      var funcSpanTemplate = '<a gf-dropdown="functionMenu" class="dropdown-toggle" ' +
-                             'data-toggle="dropdown">{{field.func}}</a><span>(</span>';
-
-      var paramTemplate = '<input type="text" style="display:none"' +
-                          ' class="input-mini tight-form-func-param"></input>';
-
-      var functionList = [
-        'count', 'mean', 'sum', 'min', 'max', 'mode', 'distinct', 'median',
-        'derivative', 'non_negative_derivative', 'stddev', 'first', 'last'
-      ];
-
-      var functionMenu = _.map(functionList, function(func) {
-        return { text: func, click: "changeFunction('" + func + "');" };
-      });
-
-      return {
-        restrict: 'A',
-        scope: {
-          field: "=",
-          getFields: "&",
-          onChange: "&",
-        },
-        link: function postLink($scope, elem) {
-          var $funcLink = $(funcSpanTemplate);
-
-          $scope.functionMenu = functionMenu;
-
-          $scope.changeFunction = function(func) {
-            $scope.field.func = func;
-            $scope.onChange();
-          };
-
-          function clickFuncParam() {
-            /*jshint validthis:true */
-
-            var $link = $(this);
-            var $input = $link.next();
-
-            $input.val($scope.field.name);
-            $input.css('width', ($link.width() + 16) + 'px');
-
-            $link.hide();
-            $input.show();
-            $input.focus();
-            $input.select();
-
-            var typeahead = $input.data('typeahead');
-            if (typeahead) {
-              $input.val('');
-              typeahead.lookup();
-            }
-          }
-
-          function inputBlur() {
-            /*jshint validthis:true */
-
-            var $input = $(this);
-            var $link = $input.prev();
-
-            if ($input.val() !== '') {
-              $link.text($input.val());
-
-              $scope.field.name = $input.val();
-              $scope.$apply($scope.onChange());
-            }
-
-            $input.hide();
-            $link.show();
-          }
-
-          function inputKeyPress(e) {
-            /*jshint validthis:true */
-
-            if(e.which === 13) {
-              inputBlur.call(this);
-            }
-          }
-
-          function inputKeyDown() {
-            /*jshint validthis:true */
-            this.style.width = (3 + this.value.length) * 8 + 'px';
-          }
-
-          function addTypeahead($input) {
-            $input.attr('data-provide', 'typeahead');
-
-            $input.typeahead({
-              source: function (query, callback) {
-                return $scope.getFields().then(function(results) {
-                  callback(results);
-                });
-              },
-              minLength: 0,
-              items: 1000,
-              updater: function (value) {
-                setTimeout(function() {
-                  inputBlur.call($input[0]);
-                }, 0);
-                return value;
-              }
-            });
-
-            var typeahead = $input.data('typeahead');
-            typeahead.lookup = function () {
-              var items;
-              this.query = this.$element.val() || '';
-              items = this.source(this.query, $.proxy(this.process, this));
-              return items ? this.process(items) : items;
-            };
-          }
-
-          function addElementsAndCompile() {
-            $funcLink.appendTo(elem);
-
-            var $paramLink = $('<a ng-click="" class="graphite-func-param-link">' + $scope.field.name + '</a>');
-            var $input = $(paramTemplate);
-
-            $paramLink.appendTo(elem);
-            $input.appendTo(elem);
-
-            $input.blur(inputBlur);
-            $input.keyup(inputKeyDown);
-            $input.keypress(inputKeyPress);
-            $paramLink.click(clickFuncParam);
-
-            addTypeahead($input);
-
-            $('<span>)</span>').appendTo(elem);
-
-            $compile(elem.contents())($scope);
-          }
-
-          addElementsAndCompile();
-
-        }
-      };
-
-    });
-
-});

+ 35 - 6
public/app/plugins/datasource/influxdb/partials/query.editor2.html

@@ -69,6 +69,39 @@
 			<div class="clearfix"></div>
 		</div>
 
+		<div class="tight-form" ng-repeat="field in target.fields">
+			<ul class="tight-form-list">
+				<li class="tight-form-item query-keyword tight-form-align" style="width: 75px;">
+					<span ng-show="$index === 0">SELECT</span>
+				</li>
+				<li>
+					<metric-segment-model property="field.func" get-options="getFunctions()" on-change="get_data()"></metric-segment>
+				</li>
+				<li>
+					<metric-segment-model property="field.name" get-options="getFields()" on-change="get_data()"></metric-segment>
+				</li>
+				<li>
+					<input type="text" class="tight-form-clear-input text-center" style="width: 70px;" ng-model="field.mathExpr" spellcheck='false' placeholder="math expr" ng-blur="get_data()">
+				</li>
+				<li class="tight-form-item query-keyword">
+					AS
+				</li>
+				<li>
+					<input type="text" class="tight-form-clear-input" style="width: 180px;" ng-model="field.asExpr" spellcheck='false' placeholder="as expr" ng-blur="get_data()">
+				</li>
+			</ul>
+
+			<ul class="tight-form-list pull-right">
+				<li class="tight-form-item last" ng-show="$index === 0">
+					<a class="pointer" ng-click="addSelect()"><i class="fa fa-plus"></i></a>
+				</li>
+				<li class="tight-form-item last" ng-show="target.fields.length > 1">
+					<a class="pointer" ng-click="removeSelect($index)"><i class="fa fa-minus"></i></a>
+				</li>
+			</ul>
+			<div class="clearfix"></div>
+		</div>
+
 		<div class="tight-form" ng-repeat="tag in target.groupBy">
 			<ul class="tight-form-list">
 				<li class="tight-form-item query-keyword tight-form-align" style="width: 75px;">
@@ -96,14 +129,10 @@
 		<div class="tight-form">
 			<ul class="tight-form-list">
 				<li class="tight-form-item query-keyword tight-form-align" style="width: 75px;">
-					SELECT
-				</li>
-				<li class="dropdown" ng-repeat="field in target.fields">
-					<span influxdb-func-editor field="field" get-fields="getFields()" on-change="fieldChanged(field)" class="tight-form-item">
-					</span>
+					ALIAS BY
 				</li>
 				<li>
-					<metric-segment segment="addFieldSegment" get-options="getFieldSegments()" on-change="addField()"></metric-segment>
+					<input type="text" class="tight-form-clear-input input-xlarge" ng-model="target.alias" spellcheck='false' placeholder="Naming pattern" ng-blur="get_data()">
 				</li>
 			</ul>
 			<div class="clearfix"></div>

+ 18 - 2
public/app/plugins/datasource/influxdb/queryBuilder.js

@@ -84,6 +84,14 @@ function (_) {
     return query;
   };
 
+
+  p._getGroupByTimeInterval = function(interval) {
+    if (interval === 'auto') {
+      return '$interval';
+    }
+    return interval;
+  };
+
   p._buildQuery = function() {
     var target = this.target;
 
@@ -103,6 +111,14 @@ function (_) {
         query += ', ';
       }
       query += field.func + '("' + field.name + '")';
+      if (field.mathExpr) {
+        query += field.mathExpr;
+      }
+      if (field.asExpr) {
+        query += ' AS "' + field.asExpr + '"';
+      } else {
+        query += ' AS "' + field.name + '"';
+      }
     }
 
     var measurement = target.measurement;
@@ -122,9 +138,9 @@ function (_) {
     for (i = 0; i < target.groupBy.length; i++) {
       var group = target.groupBy[i];
       if (group.type === 'time') {
-        query += ' time(10s)';
+        query += ' time(' + this._getGroupByTimeInterval(group.interval) + ')';
       } else {
-        query += ', ' + group.key;
+        query += ', "' + group.key + '"';
       }
     }
 

+ 17 - 27
public/app/plugins/datasource/influxdb/queryCtrl.js

@@ -29,8 +29,6 @@ function (angular, _, InfluxQueryBuilder) {
         $scope.measurementSegment = uiSegmentSrv.newSegment(target.measurement);
       }
 
-      $scope.addFieldSegment = uiSegmentSrv.newPlusButton();
-
       $scope.tagSegments = [];
       _.each(target.tags, function(tag) {
         if (!tag.operator) {
@@ -73,23 +71,13 @@ function (angular, _, InfluxQueryBuilder) {
       $scope.get_data();
     };
 
-    $scope.groupByTagUpdated = function(segment, index) {
-      if (segment.value === $scope.removeGroupBySegment.value) {
-        $scope.target.groupByTags.splice(index, 1);
-        $scope.groupBySegments.splice(index, 1);
-        $scope.$parent.get_data();
-        return;
-      }
-
-      if (index === $scope.groupBySegments.length-1) {
-        $scope.groupBySegments.push(uiSegmentSrv.newPlusButton());
-      }
-
-      segment.type = 'group-by-key';
-      segment.fake = false;
+    $scope.addSelect = function() {
+      $scope.target.fields.push({name: "select field", func: 'mean'});
+    };
 
-      $scope.target.groupByTags[index] = segment.value;
-      $scope.$parent.get_data();
+    $scope.removeSelect = function(index) {
+      $scope.target.fields.splice(index, 1);
+      $scope.get_data();
     };
 
     $scope.changeFunction = function(func) {
@@ -105,13 +93,7 @@ function (angular, _, InfluxQueryBuilder) {
     $scope.getFields = function() {
       var fieldsQuery = $scope.queryBuilder.buildExploreQuery('FIELDS');
       return $scope.datasource.metricFindQuery(fieldsQuery)
-      .then(function(results) {
-        var values = _.pluck(results, 'text');
-        if ($scope.target.fields.length > 1) {
-          values.splice(0, 0, "-- remove from select --");
-        }
-        return values;
-      });
+      .then($scope.transformToSegments(false), $scope.handleQueryError);
     };
 
     $scope.toggleQueryMode = function () {
@@ -121,8 +103,16 @@ function (angular, _, InfluxQueryBuilder) {
     $scope.getMeasurements = function () {
       var query = $scope.queryBuilder.buildExploreQuery('MEASUREMENTS');
       return $scope.datasource.metricFindQuery(query)
-      .then($scope.transformToSegments(true))
-      .then(null, $scope.handleQueryError);
+      .then($scope.transformToSegments(true), $scope.handleQueryError);
+    };
+
+    $scope.getFunctions = function () {
+      var functionList = ['count', 'mean', 'sum', 'min', 'max', 'mode', 'distinct', 'median',
+        'derivative', 'non_negative_derivative', 'stddev', 'first', 'last'
+      ];
+      return $q.when(_.map(functionList, function(func) {
+        return uiSegmentSrv.newSegment(func);
+      }));
     };
 
     $scope.handleQueryError = function(err) {

+ 67 - 44
public/test/specs/influx09-querybuilder-specs.js

@@ -6,76 +6,96 @@ define([
   describe('InfluxQueryBuilder', function() {
 
     describe('series with mesurement only', function() {
-      var builder = new InfluxQueryBuilder({
-        measurement: 'cpu',
-      });
+      it('should generate correct query', function() {
+        var builder = new InfluxQueryBuilder({
+          measurement: 'cpu',
+          groupBy: [{type: 'time', interval: 'auto'}]
+        });
 
-      var query = builder.build();
+        var query = builder.build();
 
-      it('should generate correct query', function() {
-        expect(query).to.be('SELECT mean("value") FROM "cpu" WHERE $timeFilter GROUP BY time($interval)');
+        expect(query).to.be('SELECT mean("value") AS "value" FROM "cpu" WHERE $timeFilter GROUP BY time($interval)');
       });
+    });
 
+    describe('series with math expr and as expr', function() {
+      it('should generate correct query', function() {
+        var builder = new InfluxQueryBuilder({
+          measurement: 'cpu',
+          fields: [{name: 'test', func: 'max', mathExpr: '*2', asExpr: 'new_name'}],
+          groupBy: [{type: 'time', interval: 'auto'}]
+        });
+
+        var query = builder.build();
+
+        expect(query).to.be('SELECT max("test")*2 AS "new_name" FROM "cpu" WHERE $timeFilter GROUP BY time($interval)');
+      });
     });
 
     describe('series with single tag only', function() {
-      var builder = new InfluxQueryBuilder({
-        measurement: 'cpu',
-        tags: [{key: 'hostname', value: 'server1'}]
-      });
+      it('should generate correct query', function() {
+        var builder = new InfluxQueryBuilder({
+          measurement: 'cpu',
+          groupBy: [{type: 'time', interval: 'auto'}],
+          tags: [{key: 'hostname', value: 'server1'}]
+        });
 
-      var query = builder.build();
+        var query = builder.build();
 
-      it('should generate correct query', function() {
-        expect(query).to.be('SELECT mean("value") FROM "cpu" WHERE "hostname" = \'server1\' AND $timeFilter'
+        expect(query).to.be('SELECT mean("value") AS "value" FROM "cpu" WHERE "hostname" = \'server1\' AND $timeFilter'
                             + ' GROUP BY time($interval)');
       });
 
       it('should switch regex operator with tag value is regex', function() {
-        var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: '/e.*/'}]});
+        var builder = new InfluxQueryBuilder({
+          measurement: 'cpu',
+          groupBy: [{type: 'time', interval: 'auto'}],
+          tags: [{key: 'app', value: '/e.*/'}]
+        });
+
         var query = builder.build();
-        expect(query).to.be('SELECT mean("value") FROM "cpu" WHERE "app" =~ /e.*/ AND $timeFilter GROUP BY time($interval)');
+        expect(query).to.be('SELECT mean("value") AS "value" FROM "cpu" WHERE "app" =~ /e.*/ AND $timeFilter GROUP BY time($interval)');
       });
     });
 
     describe('series with multiple fields', function() {
-      var builder = new InfluxQueryBuilder({
-        measurement: 'cpu',
-        tags: [],
-        fields: [{ name: 'tx_in', func: 'sum' }, { name: 'tx_out', func: 'mean' }]
-      });
-
-      var query = builder.build();
-
       it('should generate correct query', function() {
-        expect(query).to.be('SELECT sum("tx_in"), mean("tx_out") FROM "cpu" WHERE $timeFilter GROUP BY time($interval)');
+        var builder = new InfluxQueryBuilder({
+          measurement: 'cpu',
+          tags: [],
+          groupBy: [{type: 'time', interval: 'auto'}],
+          fields: [{ name: 'tx_in', func: 'sum' }, { name: 'tx_out', func: 'mean' }]
+        });
+
+        var query = builder.build();
+        expect(query).to.be('SELECT sum("tx_in") AS "tx_in", mean("tx_out") AS "tx_out" FROM "cpu" WHERE $timeFilter GROUP BY time($interval)');
       });
     });
 
     describe('series with multiple tags only', function() {
-      var builder = new InfluxQueryBuilder({
-        measurement: 'cpu',
-        tags: [{key: 'hostname', value: 'server1'}, {key: 'app', value: 'email', condition: "AND"}]
-      });
-
-      var query = builder.build();
-
       it('should generate correct query', function() {
-        expect(query).to.be('SELECT mean("value") FROM "cpu" WHERE "hostname" = \'server1\' AND "app" = \'email\' AND ' +
+        var builder = new InfluxQueryBuilder({
+          measurement: 'cpu',
+          groupBy: [{type: 'time', interval: 'auto'}],
+          tags: [{key: 'hostname', value: 'server1'}, {key: 'app', value: 'email', condition: "AND"}]
+        });
+
+        var query = builder.build();
+        expect(query).to.be('SELECT mean("value") AS "value" FROM "cpu" WHERE "hostname" = \'server1\' AND "app" = \'email\' AND ' +
                             '$timeFilter GROUP BY time($interval)');
       });
     });
 
     describe('series with tags OR condition', function() {
-      var builder = new InfluxQueryBuilder({
-        measurement: 'cpu',
-        tags: [{key: 'hostname', value: 'server1'}, {key: 'hostname', value: 'server2', condition: "OR"}]
-      });
-
-      var query = builder.build();
-
       it('should generate correct query', function() {
-        expect(query).to.be('SELECT mean("value") FROM "cpu" WHERE "hostname" = \'server1\' OR "hostname" = \'server2\' AND ' +
+        var builder = new InfluxQueryBuilder({
+          measurement: 'cpu',
+          groupBy: [{type: 'time', interval: 'auto'}],
+          tags: [{key: 'hostname', value: 'server1'}, {key: 'hostname', value: 'server2', condition: "OR"}]
+        });
+
+        var query = builder.build();
+        expect(query).to.be('SELECT mean("value") AS "value" FROM "cpu" WHERE "hostname" = \'server1\' OR "hostname" = \'server2\' AND ' +
                             '$timeFilter GROUP BY time($interval)');
       });
     });
@@ -85,12 +105,12 @@ define([
         var builder = new InfluxQueryBuilder({
           measurement: 'cpu',
           tags: [],
-          groupByTags: ["host"]
+          groupBy: [{type: 'time', interval: 'auto'}, {type: 'tag', key: 'host'}],
         });
 
         var query = builder.build();
-        expect(query).to.be('SELECT mean("value") FROM "cpu" WHERE $timeFilter ' +
-          'GROUP BY time($interval), "host"');
+        expect(query).to.be('SELECT mean("value") AS "value" FROM "cpu" WHERE $timeFilter ' +
+                            'GROUP BY time($interval), "host"');
       });
     });
 
@@ -103,7 +123,10 @@ define([
       });
 
       it('should handle regex measurement in tag keys query', function() {
-        var builder = new InfluxQueryBuilder({ measurement: '/.*/', tags: [] });
+        var builder = new InfluxQueryBuilder({
+          measurement: '/.*/',
+          tags: []
+        });
         var query = builder.buildExploreQuery('TAG_KEYS');
         expect(query).to.be('SHOW TAG KEYS FROM /.*/');
       });

+ 0 - 34
public/test/specs/influxdbQueryCtrl-specs.js

@@ -184,39 +184,5 @@ define([
       });
     });
 
-    describe('when adding group by', function() {
-      beforeEach(function() {
-        ctx.scope.init();
-        ctx.scope.groupByTagUpdated({value: 'host', type: 'plus-button' }, 0);
-      });
-
-      it('should add group by', function() {
-        expect(ctx.scope.target.groupByTags.length).to.be(1);
-        expect(ctx.scope.target.groupByTags[0]).to.be('host');
-      });
-
-      it('should add another plus button segment', function() {
-        expect(ctx.scope.groupBySegments[1].type).to.be('plus-button');
-      });
-    });
-
-    describe('when removing group by', function() {
-      beforeEach(function() {
-        ctx.scope.init();
-        ctx.scope.groupByTagUpdated({value: 'host', type: 'plus-button' }, 0);
-        ctx.scope.groupByTagUpdated(ctx.scope.removeGroupBySegment, 0);
-      });
-
-      it('should add group by', function() {
-        expect(ctx.scope.target.groupByTags.length).to.be(0);
-      });
-
-      it('should remove segment', function() {
-        expect(ctx.scope.groupBySegments.length).to.be(1);
-        expect(ctx.scope.groupBySegments[0].type).to.be('plus-button');
-      });
-    });
-
-
   });
 });