mssql_test.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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("When doing a query with timeFrom,timeTo,unixEpochFrom,unixEpochTo macros", func() {
  579. tsdb.Interpolate = origInterpolate
  580. query := &tsdb.TsdbQuery{
  581. TimeRange: tsdb.NewFakeTimeRange("5m", "now", fromStart),
  582. Queries: []*tsdb.Query{
  583. {
  584. DataSource: &models.DataSource{JsonData: simplejson.New()},
  585. Model: simplejson.NewFromAny(map[string]interface{}{
  586. "rawSql": `SELECT time FROM metric_values WHERE time > $__timeFrom() OR time < $__timeFrom() OR 1 < $__unixEpochFrom() OR $__unixEpochTo() > 1 ORDER BY 1`,
  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(queryResult.Meta.Get("sql").MustString(), ShouldEqual, "SELECT time FROM metric_values WHERE time > '2018-03-15T12:55:00Z' OR time < '2018-03-15T12:55:00Z' OR 1 < 1521118500 OR 1521118800 > 1 ORDER BY 1")
  598. })
  599. Convey("Given a stored procedure that takes @from and @to in epoch time", func() {
  600. sql := `
  601. IF object_id('sp_test_epoch') IS NOT NULL
  602. DROP PROCEDURE sp_test_epoch
  603. `
  604. _, err := sess.Exec(sql)
  605. So(err, ShouldBeNil)
  606. sql = `
  607. CREATE PROCEDURE sp_test_epoch(
  608. @from int,
  609. @to int,
  610. @interval nvarchar(50) = '5m',
  611. @metric nvarchar(200) = 'ALL'
  612. ) AS
  613. BEGIN
  614. DECLARE @dInterval int
  615. SELECT @dInterval = 300
  616. IF @interval = '10m'
  617. SELECT @dInterval = 600
  618. SELECT
  619. CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval as time,
  620. measurement as metric,
  621. avg(valueOne) as valueOne,
  622. avg(valueTwo) as valueTwo
  623. FROM
  624. metric_values
  625. WHERE
  626. time BETWEEN DATEADD(s, @from, '1970-01-01') AND DATEADD(s, @to, '1970-01-01') AND
  627. (@metric = 'ALL' OR measurement = @metric)
  628. GROUP BY
  629. CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval,
  630. measurement
  631. ORDER BY 1
  632. END
  633. `
  634. _, err = sess.Exec(sql)
  635. So(err, ShouldBeNil)
  636. Convey("When doing a metric query using stored procedure should return correct result", func() {
  637. query := &tsdb.TsdbQuery{
  638. Queries: []*tsdb.Query{
  639. {
  640. Model: simplejson.NewFromAny(map[string]interface{}{
  641. "rawSql": `DECLARE
  642. @from int = $__unixEpochFrom(),
  643. @to int = $__unixEpochTo()
  644. EXEC dbo.sp_test_epoch @from, @to`,
  645. "format": "time_series",
  646. }),
  647. RefId: "A",
  648. },
  649. },
  650. TimeRange: &tsdb.TimeRange{
  651. From: "1521117000000",
  652. To: "1521122100000",
  653. },
  654. }
  655. resp, err := endpoint.Query(nil, nil, query)
  656. queryResult := resp.Results["A"]
  657. So(err, ShouldBeNil)
  658. So(queryResult.Error, ShouldBeNil)
  659. So(len(queryResult.Series), ShouldEqual, 4)
  660. So(queryResult.Series[0].Name, ShouldEqual, "Metric A valueOne")
  661. So(queryResult.Series[1].Name, ShouldEqual, "Metric A valueTwo")
  662. So(queryResult.Series[2].Name, ShouldEqual, "Metric B valueOne")
  663. So(queryResult.Series[3].Name, ShouldEqual, "Metric B valueTwo")
  664. })
  665. })
  666. Convey("Given a stored procedure that takes @from and @to in datetime", func() {
  667. sql := `
  668. IF object_id('sp_test_datetime') IS NOT NULL
  669. DROP PROCEDURE sp_test_datetime
  670. `
  671. _, err := sess.Exec(sql)
  672. So(err, ShouldBeNil)
  673. sql = `
  674. CREATE PROCEDURE sp_test_datetime(
  675. @from datetime,
  676. @to datetime,
  677. @interval nvarchar(50) = '5m',
  678. @metric nvarchar(200) = 'ALL'
  679. ) AS
  680. BEGIN
  681. DECLARE @dInterval int
  682. SELECT @dInterval = 300
  683. IF @interval = '10m'
  684. SELECT @dInterval = 600
  685. SELECT
  686. CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval as time,
  687. measurement as metric,
  688. avg(valueOne) as valueOne,
  689. avg(valueTwo) as valueTwo
  690. FROM
  691. metric_values
  692. WHERE
  693. time BETWEEN @from AND @to AND
  694. (@metric = 'ALL' OR measurement = @metric)
  695. GROUP BY
  696. CAST(ROUND(DATEDIFF(second, '1970-01-01', time)/CAST(@dInterval as float), 0) as bigint)*@dInterval,
  697. measurement
  698. ORDER BY 1
  699. END
  700. `
  701. _, err = sess.Exec(sql)
  702. So(err, ShouldBeNil)
  703. Convey("When doing a metric query using stored procedure should return correct result", func() {
  704. query := &tsdb.TsdbQuery{
  705. Queries: []*tsdb.Query{
  706. {
  707. Model: simplejson.NewFromAny(map[string]interface{}{
  708. "rawSql": `DECLARE
  709. @from int = $__unixEpochFrom(),
  710. @to int = $__unixEpochTo()
  711. EXEC dbo.sp_test_epoch @from, @to`,
  712. "format": "time_series",
  713. }),
  714. RefId: "A",
  715. },
  716. },
  717. TimeRange: &tsdb.TimeRange{
  718. From: "1521117000000",
  719. To: "1521122100000",
  720. },
  721. }
  722. resp, err := endpoint.Query(nil, nil, query)
  723. queryResult := resp.Results["A"]
  724. So(err, ShouldBeNil)
  725. So(queryResult.Error, ShouldBeNil)
  726. So(len(queryResult.Series), ShouldEqual, 4)
  727. So(queryResult.Series[0].Name, ShouldEqual, "Metric A valueOne")
  728. So(queryResult.Series[1].Name, ShouldEqual, "Metric A valueTwo")
  729. So(queryResult.Series[2].Name, ShouldEqual, "Metric B valueOne")
  730. So(queryResult.Series[3].Name, ShouldEqual, "Metric B valueTwo")
  731. })
  732. })
  733. })
  734. Convey("Given a table with event data", func() {
  735. sql := `
  736. IF OBJECT_ID('dbo.[event]', 'U') IS NOT NULL
  737. DROP TABLE dbo.[event]
  738. CREATE TABLE [event] (
  739. time_sec int,
  740. description nvarchar(100),
  741. tags nvarchar(100),
  742. )
  743. `
  744. _, err := sess.Exec(sql)
  745. So(err, ShouldBeNil)
  746. type event struct {
  747. TimeSec int64
  748. Description string
  749. Tags string
  750. }
  751. events := []*event{}
  752. for _, t := range genTimeRangeByInterval(fromStart.Add(-20*time.Minute), 60*time.Minute, 25*time.Minute) {
  753. events = append(events, &event{
  754. TimeSec: t.Unix(),
  755. Description: "Someone deployed something",
  756. Tags: "deploy",
  757. })
  758. events = append(events, &event{
  759. TimeSec: t.Add(5 * time.Minute).Unix(),
  760. Description: "New support ticket registered",
  761. Tags: "ticket",
  762. })
  763. }
  764. for _, e := range events {
  765. sql = fmt.Sprintf(`
  766. INSERT [event] (time_sec, description, tags)
  767. VALUES(%d, '%s', '%s')
  768. `, e.TimeSec, e.Description, e.Tags)
  769. _, err = sess.Exec(sql)
  770. So(err, ShouldBeNil)
  771. }
  772. Convey("When doing an annotation query of deploy 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='deploy' ORDER BY 1 ASC",
  778. "format": "table",
  779. }),
  780. RefId: "Deploys",
  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["Deploys"]
  790. So(err, ShouldBeNil)
  791. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  792. })
  793. Convey("When doing an annotation query of ticket events should return expected result", func() {
  794. query := &tsdb.TsdbQuery{
  795. Queries: []*tsdb.Query{
  796. {
  797. Model: simplejson.NewFromAny(map[string]interface{}{
  798. "rawSql": "SELECT time_sec as time, description as [text], tags FROM [event] WHERE $__unixEpochFilter(time_sec) AND tags='ticket' ORDER BY 1 ASC",
  799. "format": "table",
  800. }),
  801. RefId: "Tickets",
  802. },
  803. },
  804. TimeRange: &tsdb.TimeRange{
  805. From: fmt.Sprintf("%v", fromStart.Add(-20*time.Minute).Unix()*1000),
  806. To: fmt.Sprintf("%v", fromStart.Add(40*time.Minute).Unix()*1000),
  807. },
  808. }
  809. resp, err := endpoint.Query(nil, nil, query)
  810. queryResult := resp.Results["Tickets"]
  811. So(err, ShouldBeNil)
  812. So(len(queryResult.Tables[0].Rows), ShouldEqual, 3)
  813. })
  814. Convey("When doing an annotation query with a time column in datetime format", func() {
  815. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  816. dtFormat := "2006-01-02 15:04:05.999999999"
  817. query := &tsdb.TsdbQuery{
  818. Queries: []*tsdb.Query{
  819. {
  820. Model: simplejson.NewFromAny(map[string]interface{}{
  821. "rawSql": fmt.Sprintf(`SELECT
  822. CAST('%s' AS DATETIME) as time,
  823. 'message' as text,
  824. 'tag1,tag2' as tags
  825. `, dt.Format(dtFormat)),
  826. "format": "table",
  827. }),
  828. RefId: "A",
  829. },
  830. },
  831. }
  832. resp, err := endpoint.Query(nil, nil, query)
  833. So(err, ShouldBeNil)
  834. queryResult := resp.Results["A"]
  835. So(queryResult.Error, ShouldBeNil)
  836. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  837. columns := queryResult.Tables[0].Rows[0]
  838. //Should be in milliseconds
  839. So(columns[0].(float64), ShouldEqual, float64(dt.UnixNano()/1e6))
  840. })
  841. Convey("When doing an annotation query with a time column in epoch second format should return ms", func() {
  842. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  843. query := &tsdb.TsdbQuery{
  844. Queries: []*tsdb.Query{
  845. {
  846. Model: simplejson.NewFromAny(map[string]interface{}{
  847. "rawSql": fmt.Sprintf(`SELECT
  848. %d as time,
  849. 'message' as text,
  850. 'tag1,tag2' as tags
  851. `, dt.Unix()),
  852. "format": "table",
  853. }),
  854. RefId: "A",
  855. },
  856. },
  857. }
  858. resp, err := endpoint.Query(nil, nil, query)
  859. So(err, ShouldBeNil)
  860. queryResult := resp.Results["A"]
  861. So(queryResult.Error, ShouldBeNil)
  862. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  863. columns := queryResult.Tables[0].Rows[0]
  864. //Should be in milliseconds
  865. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  866. })
  867. Convey("When doing an annotation query with a time column in epoch second format (int) should return ms", func() {
  868. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  869. query := &tsdb.TsdbQuery{
  870. Queries: []*tsdb.Query{
  871. {
  872. Model: simplejson.NewFromAny(map[string]interface{}{
  873. "rawSql": fmt.Sprintf(`SELECT
  874. cast(%d as int) as time,
  875. 'message' as text,
  876. 'tag1,tag2' as tags
  877. `, dt.Unix()),
  878. "format": "table",
  879. }),
  880. RefId: "A",
  881. },
  882. },
  883. }
  884. resp, err := endpoint.Query(nil, nil, query)
  885. So(err, ShouldBeNil)
  886. queryResult := resp.Results["A"]
  887. So(queryResult.Error, ShouldBeNil)
  888. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  889. columns := queryResult.Tables[0].Rows[0]
  890. //Should be in milliseconds
  891. So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
  892. })
  893. Convey("When doing an annotation query with a time column in epoch millisecond format should return ms", func() {
  894. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  895. query := &tsdb.TsdbQuery{
  896. Queries: []*tsdb.Query{
  897. {
  898. Model: simplejson.NewFromAny(map[string]interface{}{
  899. "rawSql": fmt.Sprintf(`SELECT
  900. %d as time,
  901. 'message' as text,
  902. 'tag1,tag2' as tags
  903. `, dt.Unix()*1000),
  904. "format": "table",
  905. }),
  906. RefId: "A",
  907. },
  908. },
  909. }
  910. resp, err := endpoint.Query(nil, nil, query)
  911. So(err, ShouldBeNil)
  912. queryResult := resp.Results["A"]
  913. So(queryResult.Error, ShouldBeNil)
  914. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  915. columns := queryResult.Tables[0].Rows[0]
  916. //Should be in milliseconds
  917. So(columns[0].(float64), ShouldEqual, float64(dt.Unix()*1000))
  918. })
  919. Convey("When doing an annotation query with a time column holding a bigint null value should return nil", func() {
  920. query := &tsdb.TsdbQuery{
  921. Queries: []*tsdb.Query{
  922. {
  923. Model: simplejson.NewFromAny(map[string]interface{}{
  924. "rawSql": `SELECT
  925. cast(null as bigint) as time,
  926. 'message' as text,
  927. 'tag1,tag2' as tags
  928. `,
  929. "format": "table",
  930. }),
  931. RefId: "A",
  932. },
  933. },
  934. }
  935. resp, err := endpoint.Query(nil, nil, query)
  936. So(err, ShouldBeNil)
  937. queryResult := resp.Results["A"]
  938. So(queryResult.Error, ShouldBeNil)
  939. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  940. columns := queryResult.Tables[0].Rows[0]
  941. //Should be in milliseconds
  942. So(columns[0], ShouldBeNil)
  943. })
  944. Convey("When doing an annotation query with a time column holding a datetime null value should return nil", func() {
  945. query := &tsdb.TsdbQuery{
  946. Queries: []*tsdb.Query{
  947. {
  948. Model: simplejson.NewFromAny(map[string]interface{}{
  949. "rawSql": `SELECT
  950. cast(null as datetime) as time,
  951. 'message' as text,
  952. 'tag1,tag2' as tags
  953. `,
  954. "format": "table",
  955. }),
  956. RefId: "A",
  957. },
  958. },
  959. }
  960. resp, err := endpoint.Query(nil, nil, query)
  961. So(err, ShouldBeNil)
  962. queryResult := resp.Results["A"]
  963. So(queryResult.Error, ShouldBeNil)
  964. So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
  965. columns := queryResult.Tables[0].Rows[0]
  966. //Should be in milliseconds
  967. So(columns[0], ShouldBeNil)
  968. })
  969. })
  970. })
  971. }
  972. func InitMSSQLTestDB(t *testing.T) *xorm.Engine {
  973. x, err := xorm.NewEngine(sqlutil.TestDB_Mssql.DriverName, strings.Replace(sqlutil.TestDB_Mssql.ConnStr, "localhost", serverIP, 1))
  974. if err != nil {
  975. t.Fatalf("Failed to init mssql db %v", err)
  976. }
  977. x.DatabaseTZ = time.UTC
  978. x.TZLocation = time.UTC
  979. // x.ShowSQL()
  980. return x
  981. }
  982. func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
  983. durationSec := int64(duration.Seconds())
  984. intervalSec := int64(interval.Seconds())
  985. timeRange := []time.Time{}
  986. for i := int64(0); i < durationSec; i += intervalSec {
  987. timeRange = append(timeRange, from)
  988. from = from.Add(time.Duration(int64(time.Second) * intervalSec))
  989. }
  990. return timeRange
  991. }