mssql_test.go 33 KB

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