postgres_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. package postgres
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "strings"
  6. "testing"
  7. "time"
  8. "github.com/go-xorm/xorm"
  9. "github.com/grafana/grafana/pkg/components/securejsondata"
  10. "github.com/grafana/grafana/pkg/components/simplejson"
  11. "github.com/grafana/grafana/pkg/models"
  12. "github.com/grafana/grafana/pkg/services/sqlstore"
  13. "github.com/grafana/grafana/pkg/services/sqlstore/sqlutil"
  14. "github.com/grafana/grafana/pkg/tsdb"
  15. _ "github.com/lib/pq"
  16. . "github.com/smartystreets/goconvey/convey"
  17. )
  18. // To run this test, set runPostgresTests=true
  19. // Or from the commandline: GRAFANA_TEST_DB=postgres go test -v ./pkg/tsdb/postgres
  20. // The tests require a PostgreSQL db named grafanadstest and a user/password grafanatest/grafanatest!
  21. // Use the docker/blocks/postgres_tests/docker-compose.yaml to spin up a
  22. // preconfigured Postgres server suitable for running these tests.
  23. // There is also a datasource and dashboard provisioned by devenv scripts that you can
  24. // use to verify that the generated data are vizualized as expected, see
  25. // devenv/README.md for setup instructions.
  26. func TestPostgres(t *testing.T) {
  27. // change to true to run the MySQL tests
  28. runPostgresTests := false
  29. // runPostgresTests := true
  30. if !(sqlstore.IsTestDbPostgres() || runPostgresTests) {
  31. t.Skip()
  32. }
  33. Convey("PostgreSQL", t, func() {
  34. x := InitPostgresTestDB(t)
  35. origXormEngine := tsdb.NewXormEngine
  36. tsdb.NewXormEngine = func(d, c string) (*xorm.Engine, error) {
  37. return x, nil
  38. }
  39. endpoint, err := newPostgresQueryEndpoint(&models.DataSource{
  40. JsonData: simplejson.New(),
  41. SecureJsonData: securejsondata.SecureJsonData{},
  42. })
  43. So(err, ShouldBeNil)
  44. sess := x.NewSession()
  45. fromStart := time.Date(2018, 3, 15, 13, 0, 0, 0, time.UTC).In(time.Local)
  46. Reset(func() {
  47. sess.Close()
  48. tsdb.NewXormEngine = origXormEngine
  49. })
  50. Convey("Given a table with different native data types", func() {
  51. sql := `
  52. DROP TABLE IF EXISTS postgres_types;
  53. CREATE TABLE postgres_types(
  54. c00_smallint smallint,
  55. c01_integer integer,
  56. c02_bigint bigint,
  57. c03_real real,
  58. c04_double double precision,
  59. c05_decimal decimal(10,2),
  60. c06_numeric numeric(10,2),
  61. c07_char char(10),
  62. c08_varchar varchar(10),
  63. c09_text text,
  64. c10_timestamp timestamp without time zone,
  65. c11_timestamptz timestamp with time zone,
  66. c12_date date,
  67. c13_time time without time zone,
  68. c14_timetz time with time zone,
  69. c15_interval interval
  70. );
  71. `
  72. _, err := sess.Exec(sql)
  73. So(err, ShouldBeNil)
  74. sql = `
  75. INSERT INTO postgres_types VALUES(
  76. 1,2,3,
  77. 4.5,6.7,1.1,1.2,
  78. 'char10','varchar10','text',
  79. now(),now(),now(),now(),now(),'15m'::interval
  80. );
  81. `
  82. _, err = sess.Exec(sql)
  83. So(err, ShouldBeNil)
  84. Convey("When doing a table query should map Postgres column types to Go types", func() {
  85. query := &tsdb.TsdbQuery{
  86. Queries: []*tsdb.Query{
  87. {
  88. Model: simplejson.NewFromAny(map[string]interface{}{
  89. "rawSql": "SELECT * FROM postgres_types",
  90. "format": "table",
  91. }),
  92. RefId: "A",
  93. },
  94. },
  95. }
  96. resp, err := endpoint.Query(nil, nil, query)
  97. So(err, ShouldBeNil)
  98. queryResult := resp.Results["A"]
  99. So(queryResult.Error, ShouldBeNil)
  100. column := queryResult.Tables[0].Rows[0]
  101. So(column[0].(int64), ShouldEqual, 1)
  102. So(column[1].(int64), ShouldEqual, 2)
  103. So(column[2].(int64), ShouldEqual, 3)
  104. So(column[3].(float64), ShouldEqual, 4.5)
  105. So(column[4].(float64), ShouldEqual, 6.7)
  106. So(column[5].(float64), ShouldEqual, 1.1)
  107. So(column[6].(float64), ShouldEqual, 1.2)
  108. So(column[7].(string), ShouldEqual, "char10 ")
  109. So(column[8].(string), ShouldEqual, "varchar10")
  110. So(column[9].(string), ShouldEqual, "text")
  111. So(column[10].(time.Time), ShouldHaveSameTypeAs, time.Now())
  112. So(column[11].(time.Time), ShouldHaveSameTypeAs, time.Now())
  113. So(column[12].(time.Time), ShouldHaveSameTypeAs, time.Now())
  114. So(column[13].(time.Time), ShouldHaveSameTypeAs, time.Now())
  115. So(column[14].(time.Time), ShouldHaveSameTypeAs, time.Now())
  116. So(column[15].(string), ShouldEqual, "00:15:00")
  117. })
  118. })
  119. Convey("Given a table with metrics that lacks data for some series ", func() {
  120. sql := `
  121. DROP TABLE IF EXISTS metric;
  122. CREATE TABLE metric (
  123. time timestamp,
  124. value integer
  125. )
  126. `
  127. _, err := sess.Exec(sql)
  128. So(err, ShouldBeNil)
  129. type metric struct {
  130. Time time.Time
  131. Value int64
  132. }
  133. series := []*metric{}
  134. firstRange := genTimeRangeByInterval(fromStart, 10*time.Minute, 10*time.Second)
  135. secondRange := genTimeRangeByInterval(fromStart.Add(20*time.Minute), 10*time.Minute, 10*time.Second)
  136. for _, t := range firstRange {
  137. series = append(series, &metric{
  138. Time: t,
  139. Value: 15,
  140. })
  141. }
  142. for _, t := range secondRange {
  143. series = append(series, &metric{
  144. Time: t,
  145. Value: 20,
  146. })
  147. }
  148. _, err = sess.InsertMulti(series)
  149. So(err, ShouldBeNil)
  150. Convey("When doing a metric query using timeGroup", func() {
  151. query := &tsdb.TsdbQuery{
  152. Queries: []*tsdb.Query{
  153. {
  154. Model: simplejson.NewFromAny(map[string]interface{}{
  155. "rawSql": "SELECT $__timeGroup(time, '5m'), avg(value) as value FROM metric GROUP BY 1 ORDER BY 1",
  156. "format": "time_series",
  157. }),
  158. RefId: "A",
  159. },
  160. },
  161. }
  162. resp, err := endpoint.Query(nil, nil, query)
  163. So(err, ShouldBeNil)
  164. queryResult := resp.Results["A"]
  165. So(queryResult.Error, ShouldBeNil)
  166. points := queryResult.Series[0].Points
  167. // without fill this should result in 4 buckets
  168. So(len(points), ShouldEqual, 4)
  169. dt := fromStart
  170. for i := 0; i < 2; i++ {
  171. aValue := points[i][0].Float64
  172. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  173. So(aValue, ShouldEqual, 15)
  174. So(aTime, ShouldEqual, dt)
  175. So(aTime.Unix()%300, ShouldEqual, 0)
  176. dt = dt.Add(5 * time.Minute)
  177. }
  178. // adjust for 10 minute gap between first and second set of points
  179. dt = dt.Add(10 * time.Minute)
  180. for i := 2; i < 4; i++ {
  181. aValue := points[i][0].Float64
  182. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  183. So(aValue, ShouldEqual, 20)
  184. So(aTime, ShouldEqual, dt)
  185. dt = dt.Add(5 * time.Minute)
  186. }
  187. })
  188. Convey("When doing a metric query using timeGroup with NULL fill enabled", func() {
  189. query := &tsdb.TsdbQuery{
  190. Queries: []*tsdb.Query{
  191. {
  192. Model: simplejson.NewFromAny(map[string]interface{}{
  193. "rawSql": "SELECT $__timeGroup(time, '5m', NULL), avg(value) as value FROM metric GROUP BY 1 ORDER BY 1",
  194. "format": "time_series",
  195. }),
  196. RefId: "A",
  197. },
  198. },
  199. TimeRange: &tsdb.TimeRange{
  200. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  201. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  202. },
  203. }
  204. resp, err := endpoint.Query(nil, nil, query)
  205. So(err, ShouldBeNil)
  206. queryResult := resp.Results["A"]
  207. So(queryResult.Error, ShouldBeNil)
  208. points := queryResult.Series[0].Points
  209. So(len(points), ShouldEqual, 7)
  210. dt := fromStart
  211. for i := 0; i < 2; i++ {
  212. aValue := points[i][0].Float64
  213. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  214. So(aValue, ShouldEqual, 15)
  215. So(aTime, ShouldEqual, dt)
  216. dt = dt.Add(5 * time.Minute)
  217. }
  218. // check for NULL values inserted by fill
  219. So(points[2][0].Valid, ShouldBeFalse)
  220. So(points[3][0].Valid, ShouldBeFalse)
  221. // adjust for 10 minute gap between first and second set of points
  222. dt = dt.Add(10 * time.Minute)
  223. for i := 4; i < 6; i++ {
  224. aValue := points[i][0].Float64
  225. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  226. So(aValue, ShouldEqual, 20)
  227. So(aTime, ShouldEqual, dt)
  228. dt = dt.Add(5 * time.Minute)
  229. }
  230. // check for NULL values inserted by fill
  231. So(points[6][0].Valid, ShouldBeFalse)
  232. })
  233. Convey("When doing a metric query using timeGroup with float fill enabled", func() {
  234. query := &tsdb.TsdbQuery{
  235. Queries: []*tsdb.Query{
  236. {
  237. Model: simplejson.NewFromAny(map[string]interface{}{
  238. "rawSql": "SELECT $__timeGroup(time, '5m', 1.5), avg(value) as value FROM metric GROUP BY 1 ORDER BY 1",
  239. "format": "time_series",
  240. }),
  241. RefId: "A",
  242. },
  243. },
  244. TimeRange: &tsdb.TimeRange{
  245. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  246. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  247. },
  248. }
  249. resp, err := endpoint.Query(nil, nil, query)
  250. So(err, ShouldBeNil)
  251. queryResult := resp.Results["A"]
  252. So(queryResult.Error, ShouldBeNil)
  253. points := queryResult.Series[0].Points
  254. So(points[3][0].Float64, ShouldEqual, 1.5)
  255. })
  256. })
  257. Convey("Given a table with metrics having multiple values and measurements", func() {
  258. type metric_values struct {
  259. Time time.Time
  260. TimeInt64 int64 `xorm:"bigint 'timeInt64' not null"`
  261. TimeInt64Nullable *int64 `xorm:"bigint 'timeInt64Nullable' null"`
  262. TimeFloat64 float64 `xorm:"double 'timeFloat64' not null"`
  263. TimeFloat64Nullable *float64 `xorm:"double 'timeFloat64Nullable' null"`
  264. TimeInt32 int32 `xorm:"int(11) 'timeInt32' not null"`
  265. TimeInt32Nullable *int32 `xorm:"int(11) 'timeInt32Nullable' null"`
  266. TimeFloat32 float32 `xorm:"double 'timeFloat32' not null"`
  267. TimeFloat32Nullable *float32 `xorm:"double 'timeFloat32Nullable' null"`
  268. Measurement string
  269. ValueOne int64 `xorm:"integer 'valueOne'"`
  270. ValueTwo int64 `xorm:"integer 'valueTwo'"`
  271. }
  272. if exist, err := sess.IsTableExist(metric_values{}); err != nil || exist {
  273. So(err, ShouldBeNil)
  274. sess.DropTable(metric_values{})
  275. }
  276. err := sess.CreateTable(metric_values{})
  277. So(err, ShouldBeNil)
  278. rand.Seed(time.Now().Unix())
  279. rnd := func(min, max int64) int64 {
  280. return rand.Int63n(max-min) + min
  281. }
  282. var tInitial time.Time
  283. series := []*metric_values{}
  284. for i, t := range genTimeRangeByInterval(fromStart.Add(-30*time.Minute), 90*time.Minute, 5*time.Minute) {
  285. if i == 0 {
  286. tInitial = t
  287. }
  288. tSeconds := t.Unix()
  289. tSecondsInt32 := int32(tSeconds)
  290. tSecondsFloat32 := float32(tSeconds)
  291. tMilliseconds := tSeconds * 1e3
  292. tMillisecondsFloat := float64(tMilliseconds)
  293. first := metric_values{
  294. Time: t,
  295. TimeInt64: tMilliseconds,
  296. TimeInt64Nullable: &(tMilliseconds),
  297. TimeFloat64: tMillisecondsFloat,
  298. TimeFloat64Nullable: &tMillisecondsFloat,
  299. TimeInt32: tSecondsInt32,
  300. TimeInt32Nullable: &tSecondsInt32,
  301. TimeFloat32: tSecondsFloat32,
  302. TimeFloat32Nullable: &tSecondsFloat32,
  303. Measurement: "Metric A",
  304. ValueOne: rnd(0, 100),
  305. ValueTwo: rnd(0, 100),
  306. }
  307. second := first
  308. second.Measurement = "Metric B"
  309. second.ValueOne = rnd(0, 100)
  310. second.ValueTwo = rnd(0, 100)
  311. series = append(series, &first)
  312. series = append(series, &second)
  313. }
  314. _, err = sess.InsertMulti(series)
  315. So(err, ShouldBeNil)
  316. Convey("When doing a metric query using epoch (int64) as time column and value column (int64) should return metric with time in milliseconds", func() {
  317. query := &tsdb.TsdbQuery{
  318. Queries: []*tsdb.Query{
  319. {
  320. Model: simplejson.NewFromAny(map[string]interface{}{
  321. "rawSql": `SELECT "timeInt64" as time, "timeInt64" FROM metric_values ORDER BY time LIMIT 1`,
  322. "format": "time_series",
  323. }),
  324. RefId: "A",
  325. },
  326. },
  327. }
  328. resp, err := endpoint.Query(nil, nil, query)
  329. So(err, ShouldBeNil)
  330. queryResult := resp.Results["A"]
  331. So(queryResult.Error, ShouldBeNil)
  332. So(len(queryResult.Series), ShouldEqual, 1)
  333. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
  334. })
  335. Convey("When doing a metric query using epoch (int64 nullable) as time column and value column (int64 nullable) should return metric with time in milliseconds", func() {
  336. query := &tsdb.TsdbQuery{
  337. Queries: []*tsdb.Query{
  338. {
  339. Model: simplejson.NewFromAny(map[string]interface{}{
  340. "rawSql": `SELECT "timeInt64Nullable" as time, "timeInt64Nullable" FROM metric_values ORDER BY time LIMIT 1`,
  341. "format": "time_series",
  342. }),
  343. RefId: "A",
  344. },
  345. },
  346. }
  347. resp, err := endpoint.Query(nil, nil, query)
  348. So(err, ShouldBeNil)
  349. queryResult := resp.Results["A"]
  350. So(queryResult.Error, ShouldBeNil)
  351. So(len(queryResult.Series), ShouldEqual, 1)
  352. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
  353. })
  354. Convey("When doing a metric query using epoch (float64) as time column and value column (float64) should return metric with time in milliseconds", func() {
  355. query := &tsdb.TsdbQuery{
  356. Queries: []*tsdb.Query{
  357. {
  358. Model: simplejson.NewFromAny(map[string]interface{}{
  359. "rawSql": `SELECT "timeFloat64" as time, "timeFloat64" FROM metric_values ORDER BY time LIMIT 1`,
  360. "format": "time_series",
  361. }),
  362. RefId: "A",
  363. },
  364. },
  365. }
  366. resp, err := endpoint.Query(nil, nil, query)
  367. So(err, ShouldBeNil)
  368. queryResult := resp.Results["A"]
  369. So(queryResult.Error, ShouldBeNil)
  370. So(len(queryResult.Series), ShouldEqual, 1)
  371. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
  372. })
  373. Convey("When doing a metric query using epoch (float64 nullable) as time column and value column (float64 nullable) should return metric with time in milliseconds", func() {
  374. query := &tsdb.TsdbQuery{
  375. Queries: []*tsdb.Query{
  376. {
  377. Model: simplejson.NewFromAny(map[string]interface{}{
  378. "rawSql": `SELECT "timeFloat64Nullable" as time, "timeFloat64Nullable" FROM metric_values ORDER BY time LIMIT 1`,
  379. "format": "time_series",
  380. }),
  381. RefId: "A",
  382. },
  383. },
  384. }
  385. resp, err := endpoint.Query(nil, nil, query)
  386. So(err, ShouldBeNil)
  387. queryResult := resp.Results["A"]
  388. So(queryResult.Error, ShouldBeNil)
  389. So(len(queryResult.Series), ShouldEqual, 1)
  390. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
  391. })
  392. Convey("When doing a metric query using epoch (int32) as time column and value column (int32) should return metric with time in milliseconds", func() {
  393. query := &tsdb.TsdbQuery{
  394. Queries: []*tsdb.Query{
  395. {
  396. Model: simplejson.NewFromAny(map[string]interface{}{
  397. "rawSql": `SELECT "timeInt32" as time, "timeInt32" FROM metric_values ORDER BY time LIMIT 1`,
  398. "format": "time_series",
  399. }),
  400. RefId: "A",
  401. },
  402. },
  403. }
  404. resp, err := endpoint.Query(nil, nil, query)
  405. So(err, ShouldBeNil)
  406. queryResult := resp.Results["A"]
  407. So(queryResult.Error, ShouldBeNil)
  408. So(len(queryResult.Series), ShouldEqual, 1)
  409. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
  410. })
  411. Convey("When doing a metric query using epoch (int32 nullable) as time column and value column (int32 nullable) should return metric with time in milliseconds", func() {
  412. query := &tsdb.TsdbQuery{
  413. Queries: []*tsdb.Query{
  414. {
  415. Model: simplejson.NewFromAny(map[string]interface{}{
  416. "rawSql": `SELECT "timeInt32Nullable" as time, "timeInt32Nullable" FROM metric_values ORDER BY time LIMIT 1`,
  417. "format": "time_series",
  418. }),
  419. RefId: "A",
  420. },
  421. },
  422. }
  423. resp, err := endpoint.Query(nil, nil, query)
  424. So(err, ShouldBeNil)
  425. queryResult := resp.Results["A"]
  426. So(queryResult.Error, ShouldBeNil)
  427. So(len(queryResult.Series), ShouldEqual, 1)
  428. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(tInitial.UnixNano()/1e6))
  429. })
  430. Convey("When doing a metric query using epoch (float32) as time column and value column (float32) should return metric with time in milliseconds", func() {
  431. query := &tsdb.TsdbQuery{
  432. Queries: []*tsdb.Query{
  433. {
  434. Model: simplejson.NewFromAny(map[string]interface{}{
  435. "rawSql": `SELECT "timeFloat32" as time, "timeFloat32" FROM metric_values ORDER BY time LIMIT 1`,
  436. "format": "time_series",
  437. }),
  438. RefId: "A",
  439. },
  440. },
  441. }
  442. resp, err := endpoint.Query(nil, nil, query)
  443. So(err, ShouldBeNil)
  444. queryResult := resp.Results["A"]
  445. So(queryResult.Error, ShouldBeNil)
  446. So(len(queryResult.Series), ShouldEqual, 1)
  447. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(float32(tInitial.Unix()))*1e3)
  448. })
  449. Convey("When doing a metric query using epoch (float32 nullable) as time column and value column (float32 nullable) should return metric with time in milliseconds", func() {
  450. query := &tsdb.TsdbQuery{
  451. Queries: []*tsdb.Query{
  452. {
  453. Model: simplejson.NewFromAny(map[string]interface{}{
  454. "rawSql": `SELECT "timeFloat32Nullable" as time, "timeFloat32Nullable" FROM metric_values ORDER BY time LIMIT 1`,
  455. "format": "time_series",
  456. }),
  457. RefId: "A",
  458. },
  459. },
  460. }
  461. resp, err := endpoint.Query(nil, nil, query)
  462. So(err, ShouldBeNil)
  463. queryResult := resp.Results["A"]
  464. So(queryResult.Error, ShouldBeNil)
  465. So(len(queryResult.Series), ShouldEqual, 1)
  466. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(float32(tInitial.Unix()))*1e3)
  467. })
  468. Convey("When doing a metric query grouping by time and select metric column should return correct series", func() {
  469. query := &tsdb.TsdbQuery{
  470. Queries: []*tsdb.Query{
  471. {
  472. Model: simplejson.NewFromAny(map[string]interface{}{
  473. "rawSql": `SELECT $__timeEpoch(time), measurement || ' - value one' as metric, "valueOne" FROM metric_values ORDER BY 1`,
  474. "format": "time_series",
  475. }),
  476. RefId: "A",
  477. },
  478. },
  479. }
  480. resp, err := endpoint.Query(nil, nil, query)
  481. So(err, ShouldBeNil)
  482. queryResult := resp.Results["A"]
  483. So(queryResult.Error, ShouldBeNil)
  484. So(len(queryResult.Series), ShouldEqual, 2)
  485. So(queryResult.Series[0].Name, ShouldEqual, "Metric A - value one")
  486. So(queryResult.Series[1].Name, ShouldEqual, "Metric B - value one")
  487. })
  488. Convey("When doing a metric query grouping by time should return correct series", func() {
  489. query := &tsdb.TsdbQuery{
  490. Queries: []*tsdb.Query{
  491. {
  492. Model: simplejson.NewFromAny(map[string]interface{}{
  493. "rawSql": `SELECT $__timeEpoch(time), "valueOne", "valueTwo" FROM metric_values ORDER BY 1`,
  494. "format": "time_series",
  495. }),
  496. RefId: "A",
  497. },
  498. },
  499. }
  500. resp, err := endpoint.Query(nil, nil, query)
  501. So(err, ShouldBeNil)
  502. queryResult := resp.Results["A"]
  503. So(queryResult.Error, ShouldBeNil)
  504. So(len(queryResult.Series), ShouldEqual, 2)
  505. So(queryResult.Series[0].Name, ShouldEqual, "valueOne")
  506. So(queryResult.Series[1].Name, ShouldEqual, "valueTwo")
  507. })
  508. })
  509. Convey("Given a table with event data", func() {
  510. type event struct {
  511. TimeSec int64
  512. Description string
  513. Tags string
  514. }
  515. if exist, err := sess.IsTableExist(event{}); err != nil || exist {
  516. So(err, ShouldBeNil)
  517. sess.DropTable(event{})
  518. }
  519. err := sess.CreateTable(event{})
  520. So(err, ShouldBeNil)
  521. events := []*event{}
  522. for _, t := range genTimeRangeByInterval(fromStart.Add(-20*time.Minute), 60*time.Minute, 25*time.Minute) {
  523. events = append(events, &event{
  524. TimeSec: t.Unix(),
  525. Description: "Someone deployed something",
  526. Tags: "deploy",
  527. })
  528. events = append(events, &event{
  529. TimeSec: t.Add(5 * time.Minute).Unix(),
  530. Description: "New support ticket registered",
  531. Tags: "ticket",
  532. })
  533. }
  534. for _, e := range events {
  535. _, err = sess.Insert(e)
  536. So(err, ShouldBeNil)
  537. }
  538. Convey("When doing an annotation query of deploy events should return expected result", func() {
  539. query := &tsdb.TsdbQuery{
  540. Queries: []*tsdb.Query{
  541. {
  542. Model: simplejson.NewFromAny(map[string]interface{}{
  543. "rawSql": `SELECT "time_sec" as time, description as text, tags FROM event WHERE $__unixEpochFilter(time_sec) AND tags='deploy' ORDER BY 1 ASC`,
  544. "format": "table",
  545. }),
  546. RefId: "Deploys",
  547. },
  548. },
  549. TimeRange: &tsdb.TimeRange{
  550. From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
  551. To: fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
  552. },
  553. }
  554. resp, err := endpoint.Query(nil, nil, query)
  555. queryResult := resp.Results["Deploys"]
  556. So(err, ShouldBeNil)
  557. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  558. })
  559. Convey("When doing an annotation query of ticket events should return expected result", func() {
  560. query := &tsdb.TsdbQuery{
  561. Queries: []*tsdb.Query{
  562. {
  563. Model: simplejson.NewFromAny(map[string]interface{}{
  564. "rawSql": `SELECT "time_sec" as time, description as text, tags FROM event WHERE $__unixEpochFilter(time_sec) AND tags='ticket' ORDER BY 1 ASC`,
  565. "format": "table",
  566. }),
  567. RefId: "Tickets",
  568. },
  569. },
  570. TimeRange: &tsdb.TimeRange{
  571. From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
  572. To: fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
  573. },
  574. }
  575. resp, err := endpoint.Query(nil, nil, query)
  576. queryResult := resp.Results["Tickets"]
  577. So(err, ShouldBeNil)
  578. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  579. })
  580. Convey("When doing an annotation query with a time column in datetime format", func() {
  581. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  582. dtFormat := "2006-01-02 15:04:05.999999999"
  583. query := &tsdb.TsdbQuery{
  584. Queries: []*tsdb.Query{
  585. {
  586. Model: simplejson.NewFromAny(map[string]interface{}{
  587. "rawSql": fmt.Sprintf(`SELECT
  588. CAST('%s' AS TIMESTAMP) as time,
  589. 'message' as text,
  590. 'tag1,tag2' as tags
  591. `, dt.Format(dtFormat)),
  592. "format": "table",
  593. }),
  594. RefId: "A",
  595. },
  596. },
  597. }
  598. resp, err := endpoint.Query(nil, nil, query)
  599. So(err, ShouldBeNil)
  600. queryResult := resp.Results["A"]
  601. So(queryResult.Error, ShouldBeNil)
  602. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  603. columns := queryResult.Tables[0].Rows[0]
  604. //Should be in milliseconds
  605. So(columns[0].(float64), ShouldEqual, float64(dt.UnixNano()/1e6))
  606. })
  607. Convey("When doing an annotation query with a time column in epoch second format should return ms", func() {
  608. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  609. query := &tsdb.TsdbQuery{
  610. Queries: []*tsdb.Query{
  611. {
  612. Model: simplejson.NewFromAny(map[string]interface{}{
  613. "rawSql": fmt.Sprintf(`SELECT
  614. %d as time,
  615. 'message' as text,
  616. 'tag1,tag2' as tags
  617. `, dt.Unix()),
  618. "format": "table",
  619. }),
  620. RefId: "A",
  621. },
  622. },
  623. }
  624. resp, err := endpoint.Query(nil, nil, query)
  625. So(err, ShouldBeNil)
  626. queryResult := resp.Results["A"]
  627. So(queryResult.Error, ShouldBeNil)
  628. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  629. columns := queryResult.Tables[0].Rows[0]
  630. //Should be in milliseconds
  631. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  632. })
  633. Convey("When doing an annotation query with a time column in epoch second format (int) should return ms", func() {
  634. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  635. query := &tsdb.TsdbQuery{
  636. Queries: []*tsdb.Query{
  637. {
  638. Model: simplejson.NewFromAny(map[string]interface{}{
  639. "rawSql": fmt.Sprintf(`SELECT
  640. cast(%d as bigint) as time,
  641. 'message' as text,
  642. 'tag1,tag2' as tags
  643. `, dt.Unix()),
  644. "format": "table",
  645. }),
  646. RefId: "A",
  647. },
  648. },
  649. }
  650. resp, err := endpoint.Query(nil, nil, query)
  651. So(err, ShouldBeNil)
  652. queryResult := resp.Results["A"]
  653. So(queryResult.Error, ShouldBeNil)
  654. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  655. columns := queryResult.Tables[0].Rows[0]
  656. //Should be in milliseconds
  657. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  658. })
  659. Convey("When doing an annotation query with a time column in epoch millisecond format should return ms", func() {
  660. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  661. query := &tsdb.TsdbQuery{
  662. Queries: []*tsdb.Query{
  663. {
  664. Model: simplejson.NewFromAny(map[string]interface{}{
  665. "rawSql": fmt.Sprintf(`SELECT
  666. %d as time,
  667. 'message' as text,
  668. 'tag1,tag2' as tags
  669. `, dt.Unix()*1000),
  670. "format": "table",
  671. }),
  672. RefId: "A",
  673. },
  674. },
  675. }
  676. resp, err := endpoint.Query(nil, nil, query)
  677. So(err, ShouldBeNil)
  678. queryResult := resp.Results["A"]
  679. So(queryResult.Error, ShouldBeNil)
  680. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  681. columns := queryResult.Tables[0].Rows[0]
  682. //Should be in milliseconds
  683. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  684. })
  685. Convey("When doing an annotation query with a time column holding a bigint null value should return nil", func() {
  686. query := &tsdb.TsdbQuery{
  687. Queries: []*tsdb.Query{
  688. {
  689. Model: simplejson.NewFromAny(map[string]interface{}{
  690. "rawSql": `SELECT
  691. cast(null as bigint) as time,
  692. 'message' as text,
  693. 'tag1,tag2' as tags
  694. `,
  695. "format": "table",
  696. }),
  697. RefId: "A",
  698. },
  699. },
  700. }
  701. resp, err := endpoint.Query(nil, nil, query)
  702. So(err, ShouldBeNil)
  703. queryResult := resp.Results["A"]
  704. So(queryResult.Error, ShouldBeNil)
  705. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  706. columns := queryResult.Tables[0].Rows[0]
  707. //Should be in milliseconds
  708. So(columns[0], ShouldBeNil)
  709. })
  710. Convey("When doing an annotation query with a time column holding a timestamp null value should return nil", func() {
  711. query := &tsdb.TsdbQuery{
  712. Queries: []*tsdb.Query{
  713. {
  714. Model: simplejson.NewFromAny(map[string]interface{}{
  715. "rawSql": `SELECT
  716. cast(null as timestamp) as time,
  717. 'message' as text,
  718. 'tag1,tag2' as tags
  719. `,
  720. "format": "table",
  721. }),
  722. RefId: "A",
  723. },
  724. },
  725. }
  726. resp, err := endpoint.Query(nil, nil, query)
  727. So(err, ShouldBeNil)
  728. queryResult := resp.Results["A"]
  729. So(queryResult.Error, ShouldBeNil)
  730. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  731. columns := queryResult.Tables[0].Rows[0]
  732. //Should be in milliseconds
  733. So(columns[0], ShouldBeNil)
  734. })
  735. })
  736. })
  737. }
  738. func InitPostgresTestDB(t *testing.T) *xorm.Engine {
  739. x, err := xorm.NewEngine(sqlutil.TestDB_Postgres.DriverName, strings.Replace(sqlutil.TestDB_Postgres.ConnStr, "dbname=grafanatest", "dbname=grafanadstest", 1))
  740. if err != nil {
  741. t.Fatalf("Failed to init postgres db %v", err)
  742. }
  743. x.DatabaseTZ = time.UTC
  744. x.TZLocation = time.UTC
  745. // x.ShowSQL()
  746. return x
  747. }
  748. func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
  749. durationSec := int64(duration.Seconds())
  750. intervalSec := int64(interval.Seconds())
  751. timeRange := []time.Time{}
  752. for i := int64(0); i < durationSec; i += intervalSec {
  753. timeRange = append(timeRange, from)
  754. from = from.Add(time.Duration(int64(time.Second) * intervalSec))
  755. }
  756. return timeRange
  757. }