mysql_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. endpoint, err := newMysqlQueryEndpoint(&models.DataSource{
  39. JsonData: simplejson.New(),
  40. SecureJsonData: securejsondata.SecureJsonData{},
  41. })
  42. So(err, ShouldBeNil)
  43. sess := x.NewSession()
  44. fromStart := time.Date(2018, 3, 15, 13, 0, 0, 0, time.UTC)
  45. Reset(func() {
  46. sess.Close()
  47. tsdb.NewXormEngine = origXormEngine
  48. })
  49. Convey("Given a table with different native data types", func() {
  50. if exists, err := sess.IsTableExist("mysql_types"); err != nil || exists {
  51. So(err, ShouldBeNil)
  52. sess.DropTable("mysql_types")
  53. }
  54. sql := "CREATE TABLE `mysql_types` ("
  55. sql += "`atinyint` tinyint(1) NOT NULL,"
  56. sql += "`avarchar` varchar(3) NOT NULL,"
  57. sql += "`achar` char(3),"
  58. sql += "`amediumint` mediumint NOT NULL,"
  59. sql += "`asmallint` smallint NOT NULL,"
  60. sql += "`abigint` bigint NOT NULL,"
  61. sql += "`aint` int(11) NOT NULL,"
  62. sql += "`adouble` double(10,2),"
  63. sql += "`anewdecimal` decimal(10,2),"
  64. sql += "`afloat` float(10,2) NOT NULL,"
  65. sql += "`atimestamp` timestamp NOT NULL,"
  66. sql += "`adatetime` datetime NOT NULL,"
  67. sql += "`atime` time NOT NULL,"
  68. sql += "`ayear` year," // Crashes xorm when running cleandb
  69. sql += "`abit` bit(1),"
  70. sql += "`atinytext` tinytext,"
  71. sql += "`atinyblob` tinyblob,"
  72. sql += "`atext` text,"
  73. sql += "`ablob` blob,"
  74. sql += "`amediumtext` mediumtext,"
  75. sql += "`amediumblob` mediumblob,"
  76. sql += "`alongtext` longtext,"
  77. sql += "`alongblob` longblob,"
  78. sql += "`aenum` enum('val1', 'val2'),"
  79. sql += "`aset` set('a', 'b', 'c', 'd'),"
  80. sql += "`adate` date,"
  81. sql += "`time_sec` datetime(6),"
  82. sql += "`aintnull` int(11),"
  83. sql += "`afloatnull` float(10,2),"
  84. sql += "`avarcharnull` varchar(3),"
  85. sql += "`adecimalnull` decimal(10,2)"
  86. sql += ") ENGINE=InnoDB DEFAULT CHARSET=latin1;"
  87. _, err := sess.Exec(sql)
  88. So(err, ShouldBeNil)
  89. sql = "INSERT INTO `mysql_types` "
  90. sql += "(`atinyint`, `avarchar`, `achar`, `amediumint`, `asmallint`, `abigint`, `aint`, `adouble`, "
  91. sql += "`anewdecimal`, `afloat`, `adatetime`, `atimestamp`, `atime`, `ayear`, `abit`, `atinytext`, "
  92. sql += "`atinyblob`, `atext`, `ablob`, `amediumtext`, `amediumblob`, `alongtext`, `alongblob`, "
  93. sql += "`aenum`, `aset`, `adate`, `time_sec`) "
  94. sql += "VALUES(1, 'abc', 'def', 1, 10, 100, 1420070400, 1.11, "
  95. sql += "2.22, 3.33, now(), current_timestamp(), '11:11:11', '2018', 1, 'tinytext', "
  96. sql += "'tinyblob', 'text', 'blob', 'mediumtext', 'mediumblob', 'longtext', 'longblob', "
  97. sql += "'val2', 'a,b', curdate(), '2018-01-01 00:01:01.123456');"
  98. _, err = sess.Exec(sql)
  99. So(err, ShouldBeNil)
  100. Convey("Query with Table format should map MySQL column types to Go types", func() {
  101. query := &tsdb.TsdbQuery{
  102. Queries: []*tsdb.Query{
  103. {
  104. Model: simplejson.NewFromAny(map[string]interface{}{
  105. "rawSql": "SELECT * FROM mysql_types",
  106. "format": "table",
  107. }),
  108. RefId: "A",
  109. },
  110. },
  111. }
  112. resp, err := endpoint.Query(nil, nil, query)
  113. So(err, ShouldBeNil)
  114. queryResult := resp.Results["A"]
  115. So(queryResult.Error, ShouldBeNil)
  116. column := queryResult.Tables[0].Rows[0]
  117. So(*column[0].(*int8), ShouldEqual, 1)
  118. So(column[1].(string), ShouldEqual, "abc")
  119. So(column[2].(string), ShouldEqual, "def")
  120. So(*column[3].(*int32), ShouldEqual, 1)
  121. So(*column[4].(*int16), ShouldEqual, 10)
  122. So(*column[5].(*int64), ShouldEqual, 100)
  123. So(*column[6].(*int32), ShouldEqual, 1420070400)
  124. So(column[7].(float64), ShouldEqual, 1.11)
  125. So(column[8].(float64), ShouldEqual, 2.22)
  126. So(*column[9].(*float32), ShouldEqual, 3.33)
  127. So(column[10].(time.Time), ShouldHappenWithin, 10*time.Second, time.Now())
  128. So(column[11].(time.Time), ShouldHappenWithin, 10*time.Second, time.Now())
  129. So(column[12].(string), ShouldEqual, "11:11:11")
  130. So(column[13].(int64), ShouldEqual, 2018)
  131. So(*column[14].(*[]byte), ShouldHaveSameTypeAs, []byte{1})
  132. So(column[15].(string), ShouldEqual, "tinytext")
  133. So(column[16].(string), ShouldEqual, "tinyblob")
  134. So(column[17].(string), ShouldEqual, "text")
  135. So(column[18].(string), ShouldEqual, "blob")
  136. So(column[19].(string), ShouldEqual, "mediumtext")
  137. So(column[20].(string), ShouldEqual, "mediumblob")
  138. So(column[21].(string), ShouldEqual, "longtext")
  139. So(column[22].(string), ShouldEqual, "longblob")
  140. So(column[23].(string), ShouldEqual, "val2")
  141. So(column[24].(string), ShouldEqual, "a,b")
  142. So(column[25].(time.Time).Format("2006-01-02T00:00:00Z"), ShouldEqual, time.Now().UTC().Format("2006-01-02T00:00:00Z"))
  143. So(column[26].(float64), ShouldEqual, float64(1.514764861123456*1e12))
  144. So(column[27], ShouldEqual, nil)
  145. So(column[28], ShouldEqual, nil)
  146. So(column[29], ShouldEqual, "")
  147. So(column[30], ShouldEqual, nil)
  148. })
  149. })
  150. Convey("Given a table with metrics that lacks data for some series ", func() {
  151. type metric struct {
  152. Time time.Time
  153. Value int64
  154. }
  155. if exist, err := sess.IsTableExist(metric{}); err != nil || exist {
  156. So(err, ShouldBeNil)
  157. sess.DropTable(metric{})
  158. }
  159. err := sess.CreateTable(metric{})
  160. So(err, ShouldBeNil)
  161. series := []*metric{}
  162. firstRange := genTimeRangeByInterval(fromStart, 10*time.Minute, 10*time.Second)
  163. secondRange := genTimeRangeByInterval(fromStart.Add(20*time.Minute), 10*time.Minute, 10*time.Second)
  164. for _, t := range firstRange {
  165. series = append(series, &metric{
  166. Time: t,
  167. Value: 15,
  168. })
  169. }
  170. for _, t := range secondRange {
  171. series = append(series, &metric{
  172. Time: t,
  173. Value: 20,
  174. })
  175. }
  176. _, err = sess.InsertMulti(series)
  177. So(err, ShouldBeNil)
  178. Convey("When doing a metric query using timeGroup", func() {
  179. query := &tsdb.TsdbQuery{
  180. Queries: []*tsdb.Query{
  181. {
  182. Model: simplejson.NewFromAny(map[string]interface{}{
  183. "rawSql": "SELECT $__timeGroup(time, '5m') as time_sec, avg(value) as value FROM metric GROUP BY 1 ORDER BY 1",
  184. "format": "time_series",
  185. }),
  186. RefId: "A",
  187. },
  188. },
  189. }
  190. resp, err := endpoint.Query(nil, nil, query)
  191. So(err, ShouldBeNil)
  192. queryResult := resp.Results["A"]
  193. So(queryResult.Error, ShouldBeNil)
  194. points := queryResult.Series[0].Points
  195. // without fill this should result in 4 buckets
  196. So(len(points), ShouldEqual, 4)
  197. dt := fromStart
  198. for i := 0; i < 2; i++ {
  199. aValue := points[i][0].Float64
  200. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  201. So(aValue, ShouldEqual, 15)
  202. So(aTime, ShouldEqual, dt)
  203. dt = dt.Add(5 * time.Minute)
  204. }
  205. // adjust for 10 minute gap between first and second set of points
  206. dt = dt.Add(10 * time.Minute)
  207. for i := 2; i < 4; i++ {
  208. aValue := points[i][0].Float64
  209. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  210. So(aValue, ShouldEqual, 20)
  211. So(aTime, ShouldEqual, dt)
  212. dt = dt.Add(5 * time.Minute)
  213. }
  214. })
  215. Convey("When doing a metric query using timeGroup with NULL fill enabled", func() {
  216. query := &tsdb.TsdbQuery{
  217. Queries: []*tsdb.Query{
  218. {
  219. Model: simplejson.NewFromAny(map[string]interface{}{
  220. "rawSql": "SELECT $__timeGroup(time, '5m', NULL) as time_sec, avg(value) as value FROM metric GROUP BY 1 ORDER BY 1",
  221. "format": "time_series",
  222. }),
  223. RefId: "A",
  224. },
  225. },
  226. TimeRange: &tsdb.TimeRange{
  227. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  228. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  229. },
  230. }
  231. resp, err := endpoint.Query(nil, nil, query)
  232. So(err, ShouldBeNil)
  233. queryResult := resp.Results["A"]
  234. So(queryResult.Error, ShouldBeNil)
  235. points := queryResult.Series[0].Points
  236. So(len(points), ShouldEqual, 7)
  237. dt := fromStart
  238. for i := 0; i < 2; i++ {
  239. aValue := points[i][0].Float64
  240. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  241. So(aValue, ShouldEqual, 15)
  242. So(aTime, ShouldEqual, dt)
  243. dt = dt.Add(5 * time.Minute)
  244. }
  245. // check for NULL values inserted by fill
  246. So(points[2][0].Valid, ShouldBeFalse)
  247. So(points[3][0].Valid, ShouldBeFalse)
  248. // adjust for 10 minute gap between first and second set of points
  249. dt = dt.Add(10 * time.Minute)
  250. for i := 4; i < 6; i++ {
  251. aValue := points[i][0].Float64
  252. aTime := time.Unix(int64(points[i][1].Float64)/1000, 0)
  253. So(aValue, ShouldEqual, 20)
  254. So(aTime, ShouldEqual, dt)
  255. dt = dt.Add(5 * time.Minute)
  256. }
  257. // check for NULL values inserted by fill
  258. So(points[6][0].Valid, ShouldBeFalse)
  259. })
  260. Convey("When doing a metric query using timeGroup with value fill enabled", func() {
  261. query := &tsdb.TsdbQuery{
  262. Queries: []*tsdb.Query{
  263. {
  264. Model: simplejson.NewFromAny(map[string]interface{}{
  265. "rawSql": "SELECT $__timeGroup(time, '5m', 1.5) as time_sec, avg(value) as value FROM metric GROUP BY 1 ORDER BY 1",
  266. "format": "time_series",
  267. }),
  268. RefId: "A",
  269. },
  270. },
  271. TimeRange: &tsdb.TimeRange{
  272. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  273. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  274. },
  275. }
  276. resp, err := endpoint.Query(nil, nil, query)
  277. So(err, ShouldBeNil)
  278. queryResult := resp.Results["A"]
  279. So(queryResult.Error, ShouldBeNil)
  280. points := queryResult.Series[0].Points
  281. So(points[3][0].Float64, ShouldEqual, 1.5)
  282. })
  283. Convey("When doing a metric query using timeGroup with last fill enabled", func() {
  284. query := &tsdb.TsdbQuery{
  285. Queries: []*tsdb.Query{
  286. {
  287. Model: simplejson.NewFromAny(map[string]interface{}{
  288. "rawSql": "SELECT $__timeGroup(time, '5m', last) as time_sec, avg(value) as value FROM metric GROUP BY 1 ORDER BY 1",
  289. "format": "time_series",
  290. }),
  291. RefId: "A",
  292. },
  293. },
  294. TimeRange: &tsdb.TimeRange{
  295. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  296. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  297. },
  298. }
  299. resp, err := endpoint.Query(nil, nil, query)
  300. So(err, ShouldBeNil)
  301. queryResult := resp.Results["A"]
  302. So(queryResult.Error, ShouldBeNil)
  303. points := queryResult.Series[0].Points
  304. So(points[2][0].Float64, ShouldEqual, 15.0)
  305. So(points[3][0].Float64, ShouldEqual, 15.0)
  306. So(points[6][0].Float64, ShouldEqual, 20.0)
  307. })
  308. })
  309. Convey("Given a table with metrics having multiple values and measurements", func() {
  310. type metric_values struct {
  311. Time time.Time `xorm:"datetime 'time' not null"`
  312. TimeNullable *time.Time `xorm:"datetime(6) 'timeNullable' null"`
  313. TimeInt64 int64 `xorm:"bigint(20) 'timeInt64' not null"`
  314. TimeInt64Nullable *int64 `xorm:"bigint(20) 'timeInt64Nullable' null"`
  315. TimeFloat64 float64 `xorm:"double 'timeFloat64' not null"`
  316. TimeFloat64Nullable *float64 `xorm:"double 'timeFloat64Nullable' null"`
  317. TimeInt32 int32 `xorm:"int(11) 'timeInt32' not null"`
  318. TimeInt32Nullable *int32 `xorm:"int(11) 'timeInt32Nullable' null"`
  319. TimeFloat32 float32 `xorm:"double 'timeFloat32' not null"`
  320. TimeFloat32Nullable *float32 `xorm:"double 'timeFloat32Nullable' null"`
  321. Measurement string
  322. ValueOne int64 `xorm:"integer 'valueOne'"`
  323. ValueTwo int64 `xorm:"integer 'valueTwo'"`
  324. }
  325. if exist, err := sess.IsTableExist(metric_values{}); err != nil || exist {
  326. So(err, ShouldBeNil)
  327. sess.DropTable(metric_values{})
  328. }
  329. err := sess.CreateTable(metric_values{})
  330. So(err, ShouldBeNil)
  331. rand.Seed(time.Now().Unix())
  332. rnd := func(min, max int64) int64 {
  333. return rand.Int63n(max-min) + min
  334. }
  335. var tInitial time.Time
  336. series := []*metric_values{}
  337. for i, t := range genTimeRangeByInterval(fromStart.Add(-30*time.Minute), 90*time.Minute, 5*time.Minute) {
  338. if i == 0 {
  339. tInitial = t
  340. }
  341. tSeconds := t.Unix()
  342. tSecondsInt32 := int32(tSeconds)
  343. tSecondsFloat32 := float32(tSeconds)
  344. tMilliseconds := tSeconds * 1e3
  345. tMillisecondsFloat := float64(tMilliseconds)
  346. t2 := t
  347. first := metric_values{
  348. Time: t,
  349. TimeNullable: &t2,
  350. TimeInt64: tMilliseconds,
  351. TimeInt64Nullable: &(tMilliseconds),
  352. TimeFloat64: tMillisecondsFloat,
  353. TimeFloat64Nullable: &tMillisecondsFloat,
  354. TimeInt32: tSecondsInt32,
  355. TimeInt32Nullable: &tSecondsInt32,
  356. TimeFloat32: tSecondsFloat32,
  357. TimeFloat32Nullable: &tSecondsFloat32,
  358. Measurement: "Metric A",
  359. ValueOne: rnd(0, 100),
  360. ValueTwo: rnd(0, 100),
  361. }
  362. second := first
  363. second.Measurement = "Metric B"
  364. second.ValueOne = rnd(0, 100)
  365. second.ValueTwo = rnd(0, 100)
  366. series = append(series, &first)
  367. series = append(series, &second)
  368. }
  369. _, err = sess.InsertMulti(series)
  370. So(err, ShouldBeNil)
  371. Convey("When doing a metric query using time 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 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 time (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 timeNullable 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 (int64) as time column and value column (int64) 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 timeInt64 as time, timeInt64 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 (int64 nullable) as time column and value column (int64 nullable) 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 timeInt64Nullable as time, timeInt64Nullable 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 (float64) as time column and value column (float64) 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 timeFloat64 as time, timeFloat64 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 (float64 nullable) as time column and value column (float64 nullable) 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 timeFloat64Nullable as time, timeFloat64Nullable 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. FocusConvey("When doing a metric query using epoch (int32) as time column and value column (int32) 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 timeInt32 as time, timeInt32 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(tInitial.UnixNano()/1e6))
  503. })
  504. 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() {
  505. query := &tsdb.TsdbQuery{
  506. Queries: []*tsdb.Query{
  507. {
  508. Model: simplejson.NewFromAny(map[string]interface{}{
  509. "rawSql": `SELECT timeInt32Nullable as time, timeInt32Nullable 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(tInitial.UnixNano()/1e6))
  522. })
  523. Convey("When doing a metric query using epoch (float32) as time column and value column (float32) should return metric with time in milliseconds", func() {
  524. query := &tsdb.TsdbQuery{
  525. Queries: []*tsdb.Query{
  526. {
  527. Model: simplejson.NewFromAny(map[string]interface{}{
  528. "rawSql": `SELECT timeFloat32 as time, timeFloat32 FROM metric_values ORDER BY time LIMIT 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, 1)
  540. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(float32(tInitial.Unix()))*1e3)
  541. })
  542. 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() {
  543. query := &tsdb.TsdbQuery{
  544. Queries: []*tsdb.Query{
  545. {
  546. Model: simplejson.NewFromAny(map[string]interface{}{
  547. "rawSql": `SELECT timeFloat32Nullable as time, timeFloat32Nullable FROM metric_values ORDER BY time LIMIT 1`,
  548. "format": "time_series",
  549. }),
  550. RefId: "A",
  551. },
  552. },
  553. }
  554. resp, err := endpoint.Query(nil, nil, query)
  555. So(err, ShouldBeNil)
  556. queryResult := resp.Results["A"]
  557. So(queryResult.Error, ShouldBeNil)
  558. So(len(queryResult.Series), ShouldEqual, 1)
  559. So(queryResult.Series[0].Points[0][1].Float64, ShouldEqual, float64(float32(tInitial.Unix()))*1e3)
  560. })
  561. Convey("When doing a metric query grouping by time and select metric column should return correct series", func() {
  562. query := &tsdb.TsdbQuery{
  563. Queries: []*tsdb.Query{
  564. {
  565. Model: simplejson.NewFromAny(map[string]interface{}{
  566. "rawSql": `SELECT $__time(time), CONCAT(measurement, ' - value one') as metric, valueOne FROM metric_values ORDER BY 1,2`,
  567. "format": "time_series",
  568. }),
  569. RefId: "A",
  570. },
  571. },
  572. }
  573. resp, err := endpoint.Query(nil, nil, query)
  574. So(err, ShouldBeNil)
  575. queryResult := resp.Results["A"]
  576. So(queryResult.Error, ShouldBeNil)
  577. So(len(queryResult.Series), ShouldEqual, 2)
  578. So(queryResult.Series[0].Name, ShouldEqual, "Metric A - value one")
  579. So(queryResult.Series[1].Name, ShouldEqual, "Metric B - value one")
  580. })
  581. Convey("When doing a metric query with metric column and multiple value columns", func() {
  582. query := &tsdb.TsdbQuery{
  583. Queries: []*tsdb.Query{
  584. {
  585. Model: simplejson.NewFromAny(map[string]interface{}{
  586. "rawSql": `SELECT $__time(time), measurement as metric, valueOne, valueTwo FROM metric_values ORDER BY 1,2`,
  587. "format": "time_series",
  588. }),
  589. RefId: "A",
  590. },
  591. },
  592. }
  593. resp, err := endpoint.Query(nil, nil, query)
  594. So(err, ShouldBeNil)
  595. queryResult := resp.Results["A"]
  596. So(queryResult.Error, ShouldBeNil)
  597. So(len(queryResult.Series), ShouldEqual, 4)
  598. So(queryResult.Series[0].Name, ShouldEqual, "Metric A valueOne")
  599. So(queryResult.Series[1].Name, ShouldEqual, "Metric A valueTwo")
  600. So(queryResult.Series[2].Name, ShouldEqual, "Metric B valueOne")
  601. So(queryResult.Series[3].Name, ShouldEqual, "Metric B valueTwo")
  602. })
  603. Convey("When doing a metric query grouping by time should return correct series", func() {
  604. query := &tsdb.TsdbQuery{
  605. Queries: []*tsdb.Query{
  606. {
  607. Model: simplejson.NewFromAny(map[string]interface{}{
  608. "rawSql": `SELECT $__time(time), valueOne, valueTwo FROM metric_values ORDER BY 1`,
  609. "format": "time_series",
  610. }),
  611. RefId: "A",
  612. },
  613. },
  614. }
  615. resp, err := endpoint.Query(nil, nil, query)
  616. So(err, ShouldBeNil)
  617. queryResult := resp.Results["A"]
  618. So(queryResult.Error, ShouldBeNil)
  619. So(len(queryResult.Series), ShouldEqual, 2)
  620. So(queryResult.Series[0].Name, ShouldEqual, "valueOne")
  621. So(queryResult.Series[1].Name, ShouldEqual, "valueTwo")
  622. })
  623. })
  624. Convey("Given a table with event data", func() {
  625. type event struct {
  626. TimeSec int64
  627. Description string
  628. Tags string
  629. }
  630. if exist, err := sess.IsTableExist(event{}); err != nil || exist {
  631. So(err, ShouldBeNil)
  632. sess.DropTable(event{})
  633. }
  634. err := sess.CreateTable(event{})
  635. So(err, ShouldBeNil)
  636. events := []*event{}
  637. for _, t := range genTimeRangeByInterval(fromStart.Add(-20*time.Minute), 60*time.Minute, 25*time.Minute) {
  638. events = append(events, &event{
  639. TimeSec: t.Unix(),
  640. Description: "Someone deployed something",
  641. Tags: "deploy",
  642. })
  643. events = append(events, &event{
  644. TimeSec: t.Add(5 * time.Minute).Unix(),
  645. Description: "New support ticket registered",
  646. Tags: "ticket",
  647. })
  648. }
  649. for _, e := range events {
  650. _, err = sess.Insert(e)
  651. So(err, ShouldBeNil)
  652. }
  653. Convey("When doing an annotation query of deploy events should return expected result", func() {
  654. query := &tsdb.TsdbQuery{
  655. Queries: []*tsdb.Query{
  656. {
  657. Model: simplejson.NewFromAny(map[string]interface{}{
  658. "rawSql": `SELECT time_sec, description as text, tags FROM event WHERE $__unixEpochFilter(time_sec) AND tags='deploy' ORDER BY 1 ASC`,
  659. "format": "table",
  660. }),
  661. RefId: "Deploys",
  662. },
  663. },
  664. TimeRange: &tsdb.TimeRange{
  665. From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
  666. To: fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
  667. },
  668. }
  669. resp, err := endpoint.Query(nil, nil, query)
  670. queryResult := resp.Results["Deploys"]
  671. So(err, ShouldBeNil)
  672. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  673. })
  674. Convey("When doing an annotation query of ticket events should return expected result", func() {
  675. query := &tsdb.TsdbQuery{
  676. Queries: []*tsdb.Query{
  677. {
  678. Model: simplejson.NewFromAny(map[string]interface{}{
  679. "rawSql": `SELECT time_sec, description as text, tags FROM event WHERE $__unixEpochFilter(time_sec) AND tags='ticket' ORDER BY 1 ASC`,
  680. "format": "table",
  681. }),
  682. RefId: "Tickets",
  683. },
  684. },
  685. TimeRange: &tsdb.TimeRange{
  686. From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
  687. To: fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
  688. },
  689. }
  690. resp, err := endpoint.Query(nil, nil, query)
  691. queryResult := resp.Results["Tickets"]
  692. So(err, ShouldBeNil)
  693. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  694. })
  695. Convey("When doing an annotation query with a time column in datetime format", func() {
  696. dt := time.Date(2018, 3, 14, 21, 20, 6, 0, time.UTC)
  697. dtFormat := "2006-01-02 15:04:05.999999999"
  698. query := &tsdb.TsdbQuery{
  699. Queries: []*tsdb.Query{
  700. {
  701. Model: simplejson.NewFromAny(map[string]interface{}{
  702. "rawSql": fmt.Sprintf(`SELECT
  703. CAST('%s' as datetime) as time_sec,
  704. 'message' as text,
  705. 'tag1,tag2' as tags
  706. `, dt.Format(dtFormat)),
  707. "format": "table",
  708. }),
  709. RefId: "A",
  710. },
  711. },
  712. }
  713. resp, err := endpoint.Query(nil, nil, query)
  714. So(err, ShouldBeNil)
  715. queryResult := resp.Results["A"]
  716. So(queryResult.Error, ShouldBeNil)
  717. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  718. columns := queryResult.Tables[0].Rows[0]
  719. //Should be in milliseconds
  720. So(columns[0].(float64), ShouldEqual, float64(dt.Unix()*1000))
  721. })
  722. Convey("When doing an annotation query with a time column in epoch second format should return ms", func() {
  723. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  724. query := &tsdb.TsdbQuery{
  725. Queries: []*tsdb.Query{
  726. {
  727. Model: simplejson.NewFromAny(map[string]interface{}{
  728. "rawSql": fmt.Sprintf(`SELECT
  729. %d as time_sec,
  730. 'message' as text,
  731. 'tag1,tag2' as tags
  732. `, dt.Unix()),
  733. "format": "table",
  734. }),
  735. RefId: "A",
  736. },
  737. },
  738. }
  739. resp, err := endpoint.Query(nil, nil, query)
  740. So(err, ShouldBeNil)
  741. queryResult := resp.Results["A"]
  742. So(queryResult.Error, ShouldBeNil)
  743. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  744. columns := queryResult.Tables[0].Rows[0]
  745. //Should be in milliseconds
  746. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  747. })
  748. Convey("When doing an annotation query with a time column in epoch second format (signed integer) should return ms", func() {
  749. dt := time.Date(2018, 3, 14, 21, 20, 6, 0, time.Local)
  750. query := &tsdb.TsdbQuery{
  751. Queries: []*tsdb.Query{
  752. {
  753. Model: simplejson.NewFromAny(map[string]interface{}{
  754. "rawSql": fmt.Sprintf(`SELECT
  755. CAST('%d' as signed integer) as time_sec,
  756. 'message' as text,
  757. 'tag1,tag2' as tags
  758. `, dt.Unix()),
  759. "format": "table",
  760. }),
  761. RefId: "A",
  762. },
  763. },
  764. }
  765. resp, err := endpoint.Query(nil, nil, query)
  766. So(err, ShouldBeNil)
  767. queryResult := resp.Results["A"]
  768. So(queryResult.Error, ShouldBeNil)
  769. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  770. columns := queryResult.Tables[0].Rows[0]
  771. //Should be in milliseconds
  772. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  773. })
  774. Convey("When doing an annotation query with a time column in epoch millisecond format should return ms", func() {
  775. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  776. query := &tsdb.TsdbQuery{
  777. Queries: []*tsdb.Query{
  778. {
  779. Model: simplejson.NewFromAny(map[string]interface{}{
  780. "rawSql": fmt.Sprintf(`SELECT
  781. %d as time_sec,
  782. 'message' as text,
  783. 'tag1,tag2' as tags
  784. `, dt.Unix()*1000),
  785. "format": "table",
  786. }),
  787. RefId: "A",
  788. },
  789. },
  790. }
  791. resp, err := endpoint.Query(nil, nil, query)
  792. So(err, ShouldBeNil)
  793. queryResult := resp.Results["A"]
  794. So(queryResult.Error, ShouldBeNil)
  795. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  796. columns := queryResult.Tables[0].Rows[0]
  797. //Should be in milliseconds
  798. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  799. })
  800. Convey("When doing an annotation query with a time column holding a unsigned integer null value should return nil", func() {
  801. query := &tsdb.TsdbQuery{
  802. Queries: []*tsdb.Query{
  803. {
  804. Model: simplejson.NewFromAny(map[string]interface{}{
  805. "rawSql": `SELECT
  806. cast(null as unsigned integer) as time_sec,
  807. 'message' as text,
  808. 'tag1,tag2' as tags
  809. `,
  810. "format": "table",
  811. }),
  812. RefId: "A",
  813. },
  814. },
  815. }
  816. resp, err := endpoint.Query(nil, nil, query)
  817. So(err, ShouldBeNil)
  818. queryResult := resp.Results["A"]
  819. So(queryResult.Error, ShouldBeNil)
  820. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  821. columns := queryResult.Tables[0].Rows[0]
  822. //Should be in milliseconds
  823. So(columns[0], ShouldBeNil)
  824. })
  825. Convey("When doing an annotation query with a time column holding a DATETIME null value should return nil", func() {
  826. query := &tsdb.TsdbQuery{
  827. Queries: []*tsdb.Query{
  828. {
  829. Model: simplejson.NewFromAny(map[string]interface{}{
  830. "rawSql": `SELECT
  831. cast(null as DATETIME) as time_sec,
  832. 'message' as text,
  833. 'tag1,tag2' as tags
  834. `,
  835. "format": "table",
  836. }),
  837. RefId: "A",
  838. },
  839. },
  840. }
  841. resp, err := endpoint.Query(nil, nil, query)
  842. So(err, ShouldBeNil)
  843. queryResult := resp.Results["A"]
  844. So(queryResult.Error, ShouldBeNil)
  845. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  846. columns := queryResult.Tables[0].Rows[0]
  847. //Should be in milliseconds
  848. So(columns[0], ShouldBeNil)
  849. })
  850. })
  851. })
  852. }
  853. func InitMySQLTestDB(t *testing.T) *xorm.Engine {
  854. x, err := xorm.NewEngine(sqlutil.TestDB_Mysql.DriverName, strings.Replace(sqlutil.TestDB_Mysql.ConnStr, "/grafana_tests", "/grafana_ds_tests", 1))
  855. if err != nil {
  856. t.Fatalf("Failed to init mysql db %v", err)
  857. }
  858. x.DatabaseTZ = time.UTC
  859. x.TZLocation = time.UTC
  860. // x.ShowSQL()
  861. return x
  862. }
  863. func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
  864. durationSec := int64(duration.Seconds())
  865. intervalSec := int64(interval.Seconds())
  866. timeRange := []time.Time{}
  867. for i := int64(0); i < durationSec; i += intervalSec {
  868. timeRange = append(timeRange, from)
  869. from = from.Add(time.Duration(int64(time.Second) * intervalSec))
  870. }
  871. return timeRange
  872. }