postgres_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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') AS time, 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) AS time, 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) AS time, 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 with metric column and multiple value columns", func() {
  489. query := &tsdb.TsdbQuery{
  490. Queries: []*tsdb.Query{
  491. {
  492. Model: simplejson.NewFromAny(map[string]interface{}{
  493. "rawSql": `SELECT $__timeEpoch(time), measurement as metric, "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, 4)
  505. So(queryResult.Series[0].Name, ShouldEqual, "Metric A valueOne")
  506. So(queryResult.Series[1].Name, ShouldEqual, "Metric A valueTwo")
  507. So(queryResult.Series[2].Name, ShouldEqual, "Metric B valueOne")
  508. So(queryResult.Series[3].Name, ShouldEqual, "Metric B valueTwo")
  509. })
  510. Convey("When doing a metric query grouping by time should return correct series", func() {
  511. query := &tsdb.TsdbQuery{
  512. Queries: []*tsdb.Query{
  513. {
  514. Model: simplejson.NewFromAny(map[string]interface{}{
  515. "rawSql": `SELECT $__timeEpoch(time), "valueOne", "valueTwo" FROM metric_values ORDER BY 1`,
  516. "format": "time_series",
  517. }),
  518. RefId: "A",
  519. },
  520. },
  521. }
  522. resp, err := endpoint.Query(nil, nil, query)
  523. So(err, ShouldBeNil)
  524. queryResult := resp.Results["A"]
  525. So(queryResult.Error, ShouldBeNil)
  526. So(len(queryResult.Series), ShouldEqual, 2)
  527. So(queryResult.Series[0].Name, ShouldEqual, "valueOne")
  528. So(queryResult.Series[1].Name, ShouldEqual, "valueTwo")
  529. })
  530. })
  531. Convey("Given a table with event data", func() {
  532. type event struct {
  533. TimeSec int64
  534. Description string
  535. Tags string
  536. }
  537. if exist, err := sess.IsTableExist(event{}); err != nil || exist {
  538. So(err, ShouldBeNil)
  539. sess.DropTable(event{})
  540. }
  541. err := sess.CreateTable(event{})
  542. So(err, ShouldBeNil)
  543. events := []*event{}
  544. for _, t := range genTimeRangeByInterval(fromStart.Add(-20*time.Minute), 60*time.Minute, 25*time.Minute) {
  545. events = append(events, &event{
  546. TimeSec: t.Unix(),
  547. Description: "Someone deployed something",
  548. Tags: "deploy",
  549. })
  550. events = append(events, &event{
  551. TimeSec: t.Add(5 * time.Minute).Unix(),
  552. Description: "New support ticket registered",
  553. Tags: "ticket",
  554. })
  555. }
  556. for _, e := range events {
  557. _, err = sess.Insert(e)
  558. So(err, ShouldBeNil)
  559. }
  560. Convey("When doing an annotation query of deploy events should return expected result", func() {
  561. query := &tsdb.TsdbQuery{
  562. Queries: []*tsdb.Query{
  563. {
  564. Model: simplejson.NewFromAny(map[string]interface{}{
  565. "rawSql": `SELECT "time_sec" as time, description as text, tags FROM event WHERE $__unixEpochFilter(time_sec) AND tags='deploy' ORDER BY 1 ASC`,
  566. "format": "table",
  567. }),
  568. RefId: "Deploys",
  569. },
  570. },
  571. TimeRange: &tsdb.TimeRange{
  572. From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
  573. To: fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
  574. },
  575. }
  576. resp, err := endpoint.Query(nil, nil, query)
  577. queryResult := resp.Results["Deploys"]
  578. So(err, ShouldBeNil)
  579. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  580. })
  581. Convey("When doing an annotation query of ticket events should return expected result", func() {
  582. query := &tsdb.TsdbQuery{
  583. Queries: []*tsdb.Query{
  584. {
  585. Model: simplejson.NewFromAny(map[string]interface{}{
  586. "rawSql": `SELECT "time_sec" as time, description as text, tags FROM event WHERE $__unixEpochFilter(time_sec) AND tags='ticket' ORDER BY 1 ASC`,
  587. "format": "table",
  588. }),
  589. RefId: "Tickets",
  590. },
  591. },
  592. TimeRange: &tsdb.TimeRange{
  593. From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
  594. To: fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
  595. },
  596. }
  597. resp, err := endpoint.Query(nil, nil, query)
  598. queryResult := resp.Results["Tickets"]
  599. So(err, ShouldBeNil)
  600. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  601. })
  602. Convey("When doing an annotation query with a time column in datetime format", func() {
  603. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  604. dtFormat := "2006-01-02 15:04:05.999999999"
  605. query := &tsdb.TsdbQuery{
  606. Queries: []*tsdb.Query{
  607. {
  608. Model: simplejson.NewFromAny(map[string]interface{}{
  609. "rawSql": fmt.Sprintf(`SELECT
  610. CAST('%s' AS TIMESTAMP) as time,
  611. 'message' as text,
  612. 'tag1,tag2' as tags
  613. `, dt.Format(dtFormat)),
  614. "format": "table",
  615. }),
  616. RefId: "A",
  617. },
  618. },
  619. }
  620. resp, err := endpoint.Query(nil, nil, query)
  621. So(err, ShouldBeNil)
  622. queryResult := resp.Results["A"]
  623. So(queryResult.Error, ShouldBeNil)
  624. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  625. columns := queryResult.Tables[0].Rows[0]
  626. //Should be in milliseconds
  627. So(columns[0].(float64), ShouldEqual, float64(dt.UnixNano()/1e6))
  628. })
  629. Convey("When doing an annotation query with a time column in epoch second format should return ms", func() {
  630. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  631. query := &tsdb.TsdbQuery{
  632. Queries: []*tsdb.Query{
  633. {
  634. Model: simplejson.NewFromAny(map[string]interface{}{
  635. "rawSql": fmt.Sprintf(`SELECT
  636. %d as time,
  637. 'message' as text,
  638. 'tag1,tag2' as tags
  639. `, dt.Unix()),
  640. "format": "table",
  641. }),
  642. RefId: "A",
  643. },
  644. },
  645. }
  646. resp, err := endpoint.Query(nil, nil, query)
  647. So(err, ShouldBeNil)
  648. queryResult := resp.Results["A"]
  649. So(queryResult.Error, ShouldBeNil)
  650. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  651. columns := queryResult.Tables[0].Rows[0]
  652. //Should be in milliseconds
  653. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  654. })
  655. Convey("When doing an annotation query with a time column in epoch second format (int) should return ms", func() {
  656. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  657. query := &tsdb.TsdbQuery{
  658. Queries: []*tsdb.Query{
  659. {
  660. Model: simplejson.NewFromAny(map[string]interface{}{
  661. "rawSql": fmt.Sprintf(`SELECT
  662. cast(%d as bigint) as time,
  663. 'message' as text,
  664. 'tag1,tag2' as tags
  665. `, dt.Unix()),
  666. "format": "table",
  667. }),
  668. RefId: "A",
  669. },
  670. },
  671. }
  672. resp, err := endpoint.Query(nil, nil, query)
  673. So(err, ShouldBeNil)
  674. queryResult := resp.Results["A"]
  675. So(queryResult.Error, ShouldBeNil)
  676. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  677. columns := queryResult.Tables[0].Rows[0]
  678. //Should be in milliseconds
  679. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  680. })
  681. Convey("When doing an annotation query with a time column in epoch millisecond format should return ms", func() {
  682. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  683. query := &tsdb.TsdbQuery{
  684. Queries: []*tsdb.Query{
  685. {
  686. Model: simplejson.NewFromAny(map[string]interface{}{
  687. "rawSql": fmt.Sprintf(`SELECT
  688. %d as time,
  689. 'message' as text,
  690. 'tag1,tag2' as tags
  691. `, dt.Unix()*1000),
  692. "format": "table",
  693. }),
  694. RefId: "A",
  695. },
  696. },
  697. }
  698. resp, err := endpoint.Query(nil, nil, query)
  699. So(err, ShouldBeNil)
  700. queryResult := resp.Results["A"]
  701. So(queryResult.Error, ShouldBeNil)
  702. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  703. columns := queryResult.Tables[0].Rows[0]
  704. //Should be in milliseconds
  705. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  706. })
  707. Convey("When doing an annotation query with a time column holding a bigint null value should return nil", func() {
  708. query := &tsdb.TsdbQuery{
  709. Queries: []*tsdb.Query{
  710. {
  711. Model: simplejson.NewFromAny(map[string]interface{}{
  712. "rawSql": `SELECT
  713. cast(null as bigint) as time,
  714. 'message' as text,
  715. 'tag1,tag2' as tags
  716. `,
  717. "format": "table",
  718. }),
  719. RefId: "A",
  720. },
  721. },
  722. }
  723. resp, err := endpoint.Query(nil, nil, query)
  724. So(err, ShouldBeNil)
  725. queryResult := resp.Results["A"]
  726. So(queryResult.Error, ShouldBeNil)
  727. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  728. columns := queryResult.Tables[0].Rows[0]
  729. //Should be in milliseconds
  730. So(columns[0], ShouldBeNil)
  731. })
  732. Convey("When doing an annotation query with a time column holding a timestamp null value should return nil", func() {
  733. query := &tsdb.TsdbQuery{
  734. Queries: []*tsdb.Query{
  735. {
  736. Model: simplejson.NewFromAny(map[string]interface{}{
  737. "rawSql": `SELECT
  738. cast(null as timestamp) as time,
  739. 'message' as text,
  740. 'tag1,tag2' as tags
  741. `,
  742. "format": "table",
  743. }),
  744. RefId: "A",
  745. },
  746. },
  747. }
  748. resp, err := endpoint.Query(nil, nil, query)
  749. So(err, ShouldBeNil)
  750. queryResult := resp.Results["A"]
  751. So(queryResult.Error, ShouldBeNil)
  752. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  753. columns := queryResult.Tables[0].Rows[0]
  754. //Should be in milliseconds
  755. So(columns[0], ShouldBeNil)
  756. })
  757. })
  758. })
  759. }
  760. func InitPostgresTestDB(t *testing.T) *xorm.Engine {
  761. x, err := xorm.NewEngine(sqlutil.TestDB_Postgres.DriverName, strings.Replace(sqlutil.TestDB_Postgres.ConnStr, "dbname=grafanatest", "dbname=grafanadstest", 1))
  762. if err != nil {
  763. t.Fatalf("Failed to init postgres db %v", err)
  764. }
  765. x.DatabaseTZ = time.UTC
  766. x.TZLocation = time.UTC
  767. // x.ShowSQL()
  768. return x
  769. }
  770. func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
  771. durationSec := int64(duration.Seconds())
  772. intervalSec := int64(interval.Seconds())
  773. timeRange := []time.Time{}
  774. for i := int64(0); i < durationSec; i += intervalSec {
  775. timeRange = append(timeRange, from)
  776. from = from.Add(time.Duration(int64(time.Second) * intervalSec))
  777. }
  778. return timeRange
  779. }