mysql_test.go 30 KB

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