mssql_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package mssql
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. "time"
  7. "github.com/go-xorm/xorm"
  8. "github.com/grafana/grafana/pkg/components/simplejson"
  9. "github.com/grafana/grafana/pkg/log"
  10. "github.com/grafana/grafana/pkg/services/sqlstore/sqlutil"
  11. "github.com/grafana/grafana/pkg/tsdb"
  12. . "github.com/smartystreets/goconvey/convey"
  13. )
  14. // To run this test, remove the Skip from SkipConvey
  15. // and set up a MSSQL db named grafana_tests and a user/password grafana/Password!
  16. // and set the variable below to the IP address of the database
  17. var serverIP string = "localhost"
  18. func TestMSSQL(t *testing.T) {
  19. SkipConvey("MSSQL", t, func() {
  20. x := InitMSSQLTestDB(t)
  21. endpoint := &MssqlQueryEndpoint{
  22. sqlEngine: &tsdb.DefaultSqlEngine{
  23. MacroEngine: NewMssqlMacroEngine(),
  24. XormEngine: x,
  25. },
  26. log: log.New("tsdb.mssql"),
  27. }
  28. sess := x.NewSession()
  29. defer sess.Close()
  30. Convey("Given a table with different native data types", func() {
  31. sql := `
  32. IF OBJECT_ID('dbo.[mssql_types]', 'U') IS NOT NULL
  33. DROP TABLE dbo.[mssql_types]
  34. CREATE TABLE [mssql_types] (
  35. c_bit bit,
  36. c_tinyint tinyint,
  37. c_smallint smallint,
  38. c_int int,
  39. c_bigint bigint,
  40. c_money money,
  41. c_smallmoney smallmoney,
  42. c_numeric numeric(10,5),
  43. c_real real,
  44. c_decimal decimal(10,2),
  45. c_float float,
  46. c_char char(10),
  47. c_varchar varchar(10),
  48. c_text text,
  49. c_nchar nchar(12),
  50. c_nvarchar nvarchar(12),
  51. c_ntext ntext,
  52. c_datetime datetime,
  53. c_datetime2 datetime2,
  54. c_smalldatetime smalldatetime,
  55. c_date date,
  56. c_time time,
  57. c_datetimeoffset datetimeoffset
  58. )
  59. `
  60. _, err := sess.Exec(sql)
  61. So(err, ShouldBeNil)
  62. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  63. dtFormat := "2006-01-02 15:04:05.999999999"
  64. d := dt.Format(dtFormat)
  65. dt2 := time.Date(2018, 3, 14, 21, 20, 6, 8896406e2, time.UTC)
  66. dt2Format := "2006-01-02 15:04:05.999999999 -07:00"
  67. d2 := dt2.Format(dt2Format)
  68. sql = fmt.Sprintf(`
  69. INSERT INTO [mssql_types]
  70. SELECT
  71. 1, 5, 20020, 980300, 1420070400, '$20000.15', '£2.15', 12345.12,
  72. 1.11, 2.22, 3.33,
  73. 'char10', 'varchar10', 'text',
  74. N'☺nchar12☺', N'☺nvarchar12☺', N'☺text☺',
  75. 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')
  76. `, d, d2, d, d, d, d2)
  77. _, err = sess.Exec(sql)
  78. So(err, ShouldBeNil)
  79. Convey("When doing a table query should map MSSQL column types to Go types", func() {
  80. query := &tsdb.TsdbQuery{
  81. Queries: []*tsdb.Query{
  82. {
  83. Model: simplejson.NewFromAny(map[string]interface{}{
  84. "rawSql": "SELECT * FROM mssql_types",
  85. "format": "table",
  86. }),
  87. RefId: "A",
  88. },
  89. },
  90. }
  91. resp, err := endpoint.Query(nil, nil, query)
  92. queryResult := resp.Results["A"]
  93. So(err, ShouldBeNil)
  94. column := queryResult.Tables[0].Rows[0]
  95. So(column[0].(bool), ShouldEqual, true)
  96. So(column[1].(int64), ShouldEqual, 5)
  97. So(column[2].(int64), ShouldEqual, 20020)
  98. So(column[3].(int64), ShouldEqual, 980300)
  99. So(column[4].(int64), ShouldEqual, 1420070400)
  100. // So(column[5].(float64), ShouldEqual, 20000.15)
  101. // So(column[6].(float64), ShouldEqual, 2.15)
  102. //So(column[7].(float64), ShouldEqual, 12345.12)
  103. So(column[8].(float64), ShouldEqual, 1.1100000143051147) // MSSQL dose not have precision for "real" datatype
  104. // fix me: MSSQL driver puts the decimal inside an array of chars. and the test fails despite the values are correct.
  105. //So(column[9].([]uint8), ShouldEqual, []uint8{'2', '.', '2', '2'})
  106. So(column[10].(float64), ShouldEqual, 3.33)
  107. So(column[11].(string), ShouldEqual, "char10 ")
  108. So(column[12].(string), ShouldEqual, "varchar10")
  109. So(column[13].(string), ShouldEqual, "text")
  110. So(column[14].(string), ShouldEqual, "☺nchar12☺ ")
  111. So(column[15].(string), ShouldEqual, "☺nvarchar12☺")
  112. So(column[16].(string), ShouldEqual, "☺text☺")
  113. So(column[17].(time.Time), ShouldEqual, dt)
  114. So(column[18].(time.Time), ShouldEqual, dt2)
  115. So(column[19].(time.Time), ShouldEqual, dt.Truncate(time.Minute))
  116. So(column[20].(time.Time), ShouldEqual, dt.Truncate(24*time.Hour))
  117. So(column[21].(time.Time), ShouldEqual, time.Date(1, 1, 1, dt.Hour(), dt.Minute(), dt.Second(), dt.Nanosecond(), time.UTC))
  118. So(column[22].(time.Time), ShouldEqual, dt2.In(time.FixedZone("UTC", int(-7*time.Hour))))
  119. })
  120. })
  121. Convey("Given a table with metrics", func() {
  122. sql := `
  123. IF OBJECT_ID('dbo.[metric]', 'U') IS NOT NULL
  124. DROP TABLE dbo.[metric]
  125. CREATE TABLE [metric] (
  126. time datetime,
  127. measurement nvarchar(100),
  128. value int
  129. )
  130. `
  131. _, err := sess.Exec(sql)
  132. So(err, ShouldBeNil)
  133. type metric struct {
  134. Time time.Time
  135. Measurement string
  136. Value int64
  137. }
  138. series := []*metric{}
  139. fromStart := time.Date(2018, 3, 15, 13, 0, 0, 0, time.UTC)
  140. firstRange := genTimeRangeByInterval(fromStart, 10*time.Minute, 10*time.Second)
  141. secondRange := genTimeRangeByInterval(fromStart.Add(20*time.Minute), 10*time.Minute, 10*time.Second)
  142. for _, t := range firstRange {
  143. series = append(series, &metric{
  144. Time: t,
  145. Measurement: "test",
  146. Value: 15,
  147. })
  148. }
  149. for _, t := range secondRange {
  150. series = append(series, &metric{
  151. Time: t,
  152. Measurement: "test",
  153. Value: 20,
  154. })
  155. }
  156. dtFormat := "2006-01-02 15:04:05.999999999"
  157. for _, s := range series {
  158. sql = fmt.Sprintf(`
  159. INSERT INTO metric (time, measurement, value)
  160. VALUES(CAST('%s' AS DATETIME), '%s', %d)
  161. `, s.Time.Format(dtFormat), s.Measurement, s.Value)
  162. _, err = sess.Exec(sql)
  163. So(err, ShouldBeNil)
  164. }
  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, measurement as metric, avg(value) as value FROM metric GROUP BY $__timeGroup(time, '5m'), measurement ORDER BY 1",
  171. "format": "time_series",
  172. }),
  173. RefId: "A",
  174. },
  175. },
  176. }
  177. resp, err := endpoint.Query(nil, nil, query)
  178. queryResult := resp.Results["A"]
  179. So(err, ShouldBeNil)
  180. So(queryResult.Error, ShouldBeNil)
  181. points := queryResult.Series[0].Points
  182. So(len(points), ShouldEqual, 4)
  183. actualValueFirst := points[0][0].Float64
  184. actualTimeFirst := time.Unix(int64(points[0][1].Float64)/1000, 0)
  185. So(actualValueFirst, ShouldEqual, 15)
  186. So(actualTimeFirst, ShouldEqual, fromStart)
  187. actualValueLast := points[3][0].Float64
  188. actualTimeLast := time.Unix(int64(points[3][1].Float64)/1000, 0)
  189. So(actualValueLast, ShouldEqual, 20)
  190. So(actualTimeLast, ShouldEqual, fromStart.Add(25*time.Minute))
  191. })
  192. Convey("When doing a metric query using timeGroup with NULL fill enabled", func() {
  193. query := &tsdb.TsdbQuery{
  194. Queries: []*tsdb.Query{
  195. {
  196. Model: simplejson.NewFromAny(map[string]interface{}{
  197. "rawSql": "SELECT $__timeGroup(time, '5m', NULL) AS time, measurement as metric, avg(value) as value FROM metric GROUP BY $__timeGroup(time, '5m'), measurement ORDER BY 1",
  198. "format": "time_series",
  199. }),
  200. RefId: "A",
  201. },
  202. },
  203. TimeRange: &tsdb.TimeRange{
  204. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  205. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  206. },
  207. }
  208. resp, err := endpoint.Query(nil, nil, query)
  209. queryResult := resp.Results["A"]
  210. So(err, ShouldBeNil)
  211. So(queryResult.Error, ShouldBeNil)
  212. points := queryResult.Series[0].Points
  213. So(len(points), ShouldEqual, 7)
  214. actualValueFirst := points[0][0].Float64
  215. actualTimeFirst := time.Unix(int64(points[0][1].Float64)/1000, 0)
  216. So(actualValueFirst, ShouldEqual, 15)
  217. So(actualTimeFirst, ShouldEqual, fromStart)
  218. actualNullPoint := points[3][0]
  219. actualNullTime := time.Unix(int64(points[3][1].Float64)/1000, 0)
  220. So(actualNullPoint.Valid, ShouldBeFalse)
  221. So(actualNullTime, ShouldEqual, fromStart.Add(15*time.Minute))
  222. actualValueLast := points[5][0].Float64
  223. actualTimeLast := time.Unix(int64(points[5][1].Float64)/1000, 0)
  224. So(actualValueLast, ShouldEqual, 20)
  225. So(actualTimeLast, ShouldEqual, fromStart.Add(25*time.Minute))
  226. actualLastNullPoint := points[6][0]
  227. actualLastNullTime := time.Unix(int64(points[6][1].Float64)/1000, 0)
  228. So(actualLastNullPoint.Valid, ShouldBeFalse)
  229. So(actualLastNullTime, ShouldEqual, fromStart.Add(30*time.Minute))
  230. })
  231. Convey("When doing a metric query using timeGroup with float fill enabled", func() {
  232. query := &tsdb.TsdbQuery{
  233. Queries: []*tsdb.Query{
  234. {
  235. Model: simplejson.NewFromAny(map[string]interface{}{
  236. "rawSql": "SELECT $__timeGroup(time, '5m', 1.5) AS time, measurement as metric, avg(value) as value FROM metric GROUP BY $__timeGroup(time, '5m'), measurement ORDER BY 1",
  237. "format": "time_series",
  238. }),
  239. RefId: "A",
  240. },
  241. },
  242. TimeRange: &tsdb.TimeRange{
  243. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  244. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  245. },
  246. }
  247. resp, err := endpoint.Query(nil, nil, query)
  248. queryResult := resp.Results["A"]
  249. So(err, ShouldBeNil)
  250. So(queryResult.Error, ShouldBeNil)
  251. points := queryResult.Series[0].Points
  252. So(points[6][0].Float64, ShouldEqual, 1.5)
  253. })
  254. })
  255. })
  256. }
  257. func InitMSSQLTestDB(t *testing.T) *xorm.Engine {
  258. x, err := xorm.NewEngine(sqlutil.TestDB_Mssql.DriverName, strings.Replace(sqlutil.TestDB_Mssql.ConnStr, "localhost", serverIP, 1))
  259. // x.ShowSQL()
  260. if err != nil {
  261. t.Fatalf("Failed to init mssql db %v", err)
  262. }
  263. sqlutil.CleanDB(x)
  264. return x
  265. }
  266. func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
  267. durationSec := int64(duration.Seconds())
  268. intervalSec := int64(interval.Seconds())
  269. timeRange := []time.Time{}
  270. for i := int64(0); i < durationSec; i += intervalSec {
  271. timeRange = append(timeRange, from)
  272. from = from.Add(time.Duration(int64(time.Second) * intervalSec))
  273. }
  274. return timeRange
  275. }