mysql_test.go 34 KB

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