mssql_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. Convey("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("Query with Table format 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. // Convey("stored procedure", func() {
  121. // sql := `
  122. // create procedure dbo.test_sp as
  123. // begin
  124. // select 1
  125. // end
  126. // `
  127. // sess.Exec(sql)
  128. // sql = `
  129. // ALTER PROCEDURE dbo.test_sp
  130. // @from int,
  131. // @to int
  132. // AS
  133. // BEGIN
  134. // select
  135. // GETDATE() AS Time,
  136. // 1 as value,
  137. // 'metric' as metric
  138. // END
  139. // `
  140. // _, err := sess.Exec(sql)
  141. // So(err, ShouldBeNil)
  142. // sql = `
  143. // EXEC dbo.test_sp 1, 2
  144. // `
  145. // _, err = sess.Exec(sql)
  146. // So(err, ShouldBeNil)
  147. // })
  148. })
  149. Convey("Given a table with metrics", func() {
  150. sql := `
  151. IF OBJECT_ID('dbo.[metric]', 'U') IS NOT NULL
  152. DROP TABLE dbo.[metric]
  153. CREATE TABLE [metric] (
  154. time datetime,
  155. measurement nvarchar(100),
  156. value int
  157. )
  158. `
  159. _, err := sess.Exec(sql)
  160. So(err, ShouldBeNil)
  161. type metric struct {
  162. Time time.Time
  163. Measurement string
  164. Value int64
  165. }
  166. series := []*metric{}
  167. fromStart := time.Date(2018, 3, 15, 13, 0, 0, 0, time.UTC)
  168. firstRange := genTimeRangeByInterval(fromStart, 10*time.Minute, 10*time.Second)
  169. secondRange := genTimeRangeByInterval(fromStart.Add(20*time.Minute), 10*time.Minute, 10*time.Second)
  170. for _, t := range firstRange {
  171. series = append(series, &metric{
  172. Time: t,
  173. Measurement: "test",
  174. Value: 15,
  175. })
  176. }
  177. for _, t := range secondRange {
  178. series = append(series, &metric{
  179. Time: t,
  180. Measurement: "test",
  181. Value: 20,
  182. })
  183. }
  184. dtFormat := "2006-01-02 15:04:05.999999999"
  185. for _, s := range series {
  186. sql = fmt.Sprintf(`
  187. INSERT INTO metric (time, measurement, value)
  188. VALUES(CAST('%s' AS DATETIME), '%s', %d)
  189. `, s.Time.Format(dtFormat), s.Measurement, s.Value)
  190. _, err = sess.Exec(sql)
  191. So(err, ShouldBeNil)
  192. }
  193. Convey("When doing a metric query using timeGroup", func() {
  194. query := &tsdb.TsdbQuery{
  195. Queries: []*tsdb.Query{
  196. {
  197. Model: simplejson.NewFromAny(map[string]interface{}{
  198. "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",
  199. "format": "time_series",
  200. }),
  201. RefId: "A",
  202. },
  203. },
  204. }
  205. resp, err := endpoint.Query(nil, nil, query)
  206. queryResult := resp.Results["A"]
  207. So(err, ShouldBeNil)
  208. So(queryResult.Error, ShouldBeNil)
  209. points := queryResult.Series[0].Points
  210. So(len(points), ShouldEqual, 4)
  211. actualValueFirst := points[0][0].Float64
  212. actualTimeFirst := time.Unix(int64(points[0][1].Float64)/1000, 0)
  213. So(actualValueFirst, ShouldEqual, 15)
  214. So(actualTimeFirst, ShouldEqual, fromStart)
  215. actualValueLast := points[3][0].Float64
  216. actualTimeLast := time.Unix(int64(points[3][1].Float64)/1000, 0)
  217. So(actualValueLast, ShouldEqual, 20)
  218. So(actualTimeLast, ShouldEqual, fromStart.Add(25*time.Minute))
  219. })
  220. Convey("When doing a metric query using timeGroup with NULL fill enabled", func() {
  221. query := &tsdb.TsdbQuery{
  222. Queries: []*tsdb.Query{
  223. {
  224. Model: simplejson.NewFromAny(map[string]interface{}{
  225. "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",
  226. "format": "time_series",
  227. }),
  228. RefId: "A",
  229. },
  230. },
  231. TimeRange: &tsdb.TimeRange{
  232. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  233. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  234. },
  235. }
  236. resp, err := endpoint.Query(nil, nil, query)
  237. queryResult := resp.Results["A"]
  238. So(err, ShouldBeNil)
  239. So(queryResult.Error, ShouldBeNil)
  240. points := queryResult.Series[0].Points
  241. So(len(points), ShouldEqual, 7)
  242. actualValueFirst := points[0][0].Float64
  243. actualTimeFirst := time.Unix(int64(points[0][1].Float64)/1000, 0)
  244. So(actualValueFirst, ShouldEqual, 15)
  245. So(actualTimeFirst, ShouldEqual, fromStart)
  246. actualNullPoint := points[3][0]
  247. actualNullTime := time.Unix(int64(points[3][1].Float64)/1000, 0)
  248. So(actualNullPoint.Valid, ShouldBeFalse)
  249. So(actualNullTime, ShouldEqual, fromStart.Add(15*time.Minute))
  250. actualValueLast := points[5][0].Float64
  251. actualTimeLast := time.Unix(int64(points[5][1].Float64)/1000, 0)
  252. So(actualValueLast, ShouldEqual, 20)
  253. So(actualTimeLast, ShouldEqual, fromStart.Add(25*time.Minute))
  254. actualLastNullPoint := points[6][0]
  255. actualLastNullTime := time.Unix(int64(points[6][1].Float64)/1000, 0)
  256. So(actualLastNullPoint.Valid, ShouldBeFalse)
  257. So(actualLastNullTime, ShouldEqual, fromStart.Add(30*time.Minute))
  258. })
  259. Convey("When doing a metric query using timeGroup with float fill enabled", func() {
  260. query := &tsdb.TsdbQuery{
  261. Queries: []*tsdb.Query{
  262. {
  263. Model: simplejson.NewFromAny(map[string]interface{}{
  264. "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",
  265. "format": "time_series",
  266. }),
  267. RefId: "A",
  268. },
  269. },
  270. TimeRange: &tsdb.TimeRange{
  271. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  272. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  273. },
  274. }
  275. resp, err := endpoint.Query(nil, nil, query)
  276. queryResult := resp.Results["A"]
  277. So(err, ShouldBeNil)
  278. So(queryResult.Error, ShouldBeNil)
  279. points := queryResult.Series[0].Points
  280. So(points[6][0].Float64, ShouldEqual, 1.5)
  281. })
  282. })
  283. })
  284. }
  285. func InitMSSQLTestDB(t *testing.T) *xorm.Engine {
  286. x, err := xorm.NewEngine(sqlutil.TestDB_Mssql.DriverName, strings.Replace(sqlutil.TestDB_Mssql.ConnStr, "localhost", serverIP, 1))
  287. // x.ShowSQL()
  288. if err != nil {
  289. t.Fatalf("Failed to init mssql db %v", err)
  290. }
  291. sqlutil.CleanDB(x)
  292. return x
  293. }
  294. func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
  295. durationSec := int64(duration.Seconds())
  296. intervalSec := int64(interval.Seconds())
  297. timeRange := []time.Time{}
  298. for i := int64(0); i < durationSec; i += intervalSec {
  299. timeRange = append(timeRange, from)
  300. from = from.Add(time.Duration(int64(time.Second) * intervalSec))
  301. }
  302. return timeRange
  303. }