mysql_test.go 35 KB

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