mssql_test.go 35 KB

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