From dc22e24642f79b1130de2fc4f15d911c2973f5d0 Mon Sep 17 00:00:00 2001 From: Sven Klemm Date: Wed, 1 Aug 2018 15:06:18 +0200 Subject: [PATCH] add compatibility code to handle pre 5.3 usage --- pkg/tsdb/postgres/macros.go | 17 +++++++++++++++++ pkg/tsdb/postgres/macros_test.go | 19 ++++++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/pkg/tsdb/postgres/macros.go b/pkg/tsdb/postgres/macros.go index fa887032c5d..9e337caf3ec 100644 --- a/pkg/tsdb/postgres/macros.go +++ b/pkg/tsdb/postgres/macros.go @@ -30,6 +30,23 @@ func (m *postgresMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.Tim var macroError error sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string { + + // detect if $__timeGroup is supposed to add AS time for pre 5.3 compatibility + // if there is a ',' directly after the macro call $__timeGroup is probably used + // in the old way. Inside window function ORDER BY $__timeGroup will be followed + // by ')' + if groups[1] == "__timeGroup" { + if index := strings.Index(sql, groups[0]); index >= 0 { + index += len(groups[0]) + if len(sql) > index { + // check for character after macro expression + if sql[index] == ',' { + groups[1] = "__timeGroupAlias" + } + } + } + } + args := strings.Split(groups[2], ",") for i, arg := range args { args[i] = strings.Trim(arg, " ") diff --git a/pkg/tsdb/postgres/macros_test.go b/pkg/tsdb/postgres/macros_test.go index ec74470a803..beeea93893b 100644 --- a/pkg/tsdb/postgres/macros_test.go +++ b/pkg/tsdb/postgres/macros_test.go @@ -48,14 +48,27 @@ func TestMacroEngine(t *testing.T) { So(sql, ShouldEqual, fmt.Sprintf("select '%s'", from.Format(time.RFC3339))) }) + Convey("interpolate __timeGroup function pre 5.3 compatibility", func() { + + sql, err := engine.Interpolate(query, timeRange, "SELECT $__timeGroup(time_column,'5m'), value") + So(err, ShouldBeNil) + + So(sql, ShouldEqual, "SELECT floor(extract(epoch from time_column)/300)*300 AS \"time\", value") + + sql, err = engine.Interpolate(query, timeRange, "SELECT $__timeGroup(time_column,'5m') as time, value") + So(err, ShouldBeNil) + + So(sql, ShouldEqual, "SELECT floor(extract(epoch from time_column)/300)*300 as time, value") + }) + Convey("interpolate __timeGroup function", func() { - sql, err := engine.Interpolate(query, timeRange, "$__timeGroup(time_column,'5m')") + sql, err := engine.Interpolate(query, timeRange, "SELECT $__timeGroup(time_column,'5m')") So(err, ShouldBeNil) - sql2, err := engine.Interpolate(query, timeRange, "$__timeGroupAlias(time_column,'5m')") + sql2, err := engine.Interpolate(query, timeRange, "SELECT $__timeGroupAlias(time_column,'5m')") So(err, ShouldBeNil) - So(sql, ShouldEqual, "floor(extract(epoch from time_column)/300)*300") + So(sql, ShouldEqual, "SELECT floor(extract(epoch from time_column)/300)*300") So(sql2, ShouldEqual, sql+" AS \"time\"") })