From 391fb53743f3c4224bd1aded2832a43056063b91 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Wed, 19 Sep 2018 14:46:05 +0100 Subject: [PATCH] Add SQL function time.week() --- sql/funcs.go | 1 + util/fncs/fnc.go | 2 ++ util/fncs/time.go | 14 ++++++++++++++ util/fncs/time_test.go | 19 +++++++++++++++++++ 4 files changed, 36 insertions(+) diff --git a/sql/funcs.go b/sql/funcs.go index 64ba7a99..b612dd96 100644 --- a/sql/funcs.go +++ b/sql/funcs.go @@ -193,6 +193,7 @@ var funcs = map[string]map[int]interface{}{ "time.nano": {0: nil, 1: nil}, "time.secs": {0: nil, 1: nil}, "time.unix": {0: nil, 1: nil}, + "time.week": {0: nil, 1: nil}, "time.year": {0: nil, 1: nil}, // Url implementation diff --git a/util/fncs/fnc.go b/util/fncs/fnc.go index 8b4f529b..c984ec86 100644 --- a/util/fncs/fnc.go +++ b/util/fncs/fnc.go @@ -248,6 +248,8 @@ func Run(ctx context.Context, name string, args ...interface{}) (interface{}, er return timeSecs(ctx, args...) case "time.unix": return timeUnix(ctx, args...) + case "time.week": + return timeWeek(ctx, args...) case "time.year": return timeYear(ctx, args...) diff --git a/util/fncs/time.go b/util/fncs/time.go index 3bec79b0..d2008704 100644 --- a/util/fncs/time.go +++ b/util/fncs/time.go @@ -143,6 +143,20 @@ func timeUnix(ctx context.Context, args ...interface{}) (interface{}, error) { return nil, nil } +func timeWeek(ctx context.Context, args ...interface{}) (interface{}, error) { + switch len(args) { + case 0: + _, w := time.Now().ISOWeek() + return float64(w), nil + case 1: + if v, ok := ensureTime(args[0]); ok { + _, w := v.ISOWeek() + return float64(w), nil + } + } + return nil, nil +} + func timeYear(ctx context.Context, args ...interface{}) (interface{}, error) { switch len(args) { case 0: diff --git a/util/fncs/time_test.go b/util/fncs/time_test.go index 0e28e3c4..caa21754 100644 --- a/util/fncs/time_test.go +++ b/util/fncs/time_test.go @@ -213,6 +213,25 @@ func TestTime(t *testing.T) { So(res, ShouldEqual, nil) }) + Convey("time.week() works properly", t, func() { + res, _ := Run(context.Background(), "time.week") + So(res, ShouldHaveSameTypeAs, float64(0)) + _, val := now.ISOWeek() + So(res, ShouldBeGreaterThanOrEqualTo, val) + }) + + Convey("time.week(a) works properly", t, func() { + res, _ := Run(context.Background(), "time.week", old) + So(res, ShouldHaveSameTypeAs, float64(0)) + So(res, ShouldEqual, 1) + }) + + Convey("time.week(a,b,c) errors properly", t, func() { + res, _ := Run(context.Background(), "time.week", "one", "two") + So(res, ShouldHaveSameTypeAs, nil) + So(res, ShouldEqual, nil) + }) + Convey("time.year() works properly", t, func() { res, _ := Run(context.Background(), "time.year") So(res, ShouldHaveSameTypeAs, float64(0))