mssql_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. sql := `
  31. IF OBJECT_ID('dbo.[mssql_types]', 'U') IS NOT NULL
  32. DROP TABLE dbo.[mssql_types]
  33. CREATE TABLE [mssql_types] (
  34. c_bit bit,
  35. c_tinyint tinyint,
  36. c_smallint smallint,
  37. c_int int,
  38. c_bigint bigint,
  39. c_money money,
  40. c_smallmoney smallmoney,
  41. c_numeric numeric(10,5),
  42. c_real real,
  43. c_decimal decimal(10,2),
  44. c_float float,
  45. c_char char(10),
  46. c_varchar varchar(10),
  47. c_text text,
  48. c_nchar nchar(12),
  49. c_nvarchar nvarchar(12),
  50. c_ntext ntext,
  51. c_datetime datetime,
  52. c_datetime2 datetime2,
  53. c_smalldatetime smalldatetime,
  54. c_date date,
  55. c_time time,
  56. c_datetimeoffset datetimeoffset
  57. )
  58. IF OBJECT_ID('dbo.[metric]', 'U') IS NOT NULL
  59. DROP TABLE dbo.[metric]
  60. CREATE TABLE [metric] (
  61. time datetime,
  62. measurement nvarchar(100),
  63. value int
  64. )
  65. `
  66. _, err := sess.Exec(sql)
  67. So(err, ShouldBeNil)
  68. // type metric struct {
  69. // Time time.Time
  70. // Measurement string
  71. // Value int64
  72. // }
  73. // series := []*metric{}
  74. // from := time.Now().Truncate(60 * time.Minute).Add((-30 * time.Minute))
  75. // for _, t := range genTimeRangeByInterval(from, 10*time.Minute, 10*time.Second) {
  76. // series = append(series, &metric{
  77. // Time: t,
  78. // Measurement: "test",
  79. // Value: 0,
  80. // })
  81. // }
  82. // for _, t := range genTimeRangeByInterval(from.Add(20*time.Minute), 10*time.Minute, 10*time.Second) {
  83. // series = append(series, &metric{
  84. // Time: t,
  85. // Measurement: "test",
  86. // Value: 0,
  87. // })
  88. // }
  89. // rowsAffected, err := sess.InsertMulti(series)
  90. // So(err, ShouldBeNil)
  91. // So(rowsAffected, ShouldBeGreaterThan, 0)
  92. dt := time.Date(2018, 3, 14, 21, 20, 6, 527e6, time.UTC)
  93. dtFormat := "2006-01-02 15:04:05.999999999"
  94. d := dt.Format(dtFormat)
  95. dt2 := time.Date(2018, 3, 14, 21, 20, 6, 8896406e2, time.UTC)
  96. dt2Format := "2006-01-02 15:04:05.999999999 -07:00"
  97. d2 := dt2.Format(dt2Format)
  98. sql = fmt.Sprintf(`
  99. INSERT INTO [mssql_types]
  100. SELECT
  101. 1, 5, 20020, 980300, 1420070400, '$20000.15', '£2.15', 12345.12,
  102. 1.11, 2.22, 3.33,
  103. 'char10', 'varchar10', 'text',
  104. N'☺nchar12☺', N'☺nvarchar12☺', N'☺text☺',
  105. 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')
  106. `, d, d2, d, d, d, d2)
  107. _, err = sess.Exec(sql)
  108. So(err, ShouldBeNil)
  109. Convey("Query with Table format should map MSSQL column types to Go types", func() {
  110. query := &tsdb.TsdbQuery{
  111. Queries: []*tsdb.Query{
  112. {
  113. Model: simplejson.NewFromAny(map[string]interface{}{
  114. "rawSql": "SELECT * FROM mssql_types",
  115. "format": "table",
  116. }),
  117. RefId: "A",
  118. },
  119. },
  120. }
  121. resp, err := endpoint.Query(nil, nil, query)
  122. queryResult := resp.Results["A"]
  123. So(err, ShouldBeNil)
  124. column := queryResult.Tables[0].Rows[0]
  125. So(column[0].(bool), ShouldEqual, true)
  126. So(column[1].(int64), ShouldEqual, 5)
  127. So(column[2].(int64), ShouldEqual, 20020)
  128. So(column[3].(int64), ShouldEqual, 980300)
  129. So(column[4].(int64), ShouldEqual, 1420070400)
  130. // So(column[5].(float64), ShouldEqual, 20000.15)
  131. // So(column[6].(float64), ShouldEqual, 2.15)
  132. //So(column[7].(float64), ShouldEqual, 12345.12)
  133. So(column[8].(float64), ShouldEqual, 1.1100000143051147) // MSSQL dose not have precision for "real" datatype
  134. // fix me: MSSQL driver puts the decimal inside an array of chars. and the test fails despite the values are correct.
  135. //So(column[9].([]uint8), ShouldEqual, []uint8{'2', '.', '2', '2'})
  136. So(column[10].(float64), ShouldEqual, 3.33)
  137. So(column[11].(string), ShouldEqual, "char10 ")
  138. So(column[12].(string), ShouldEqual, "varchar10")
  139. So(column[13].(string), ShouldEqual, "text")
  140. So(column[14].(string), ShouldEqual, "☺nchar12☺ ")
  141. So(column[15].(string), ShouldEqual, "☺nvarchar12☺")
  142. So(column[16].(string), ShouldEqual, "☺text☺")
  143. So(column[17].(time.Time), ShouldEqual, dt)
  144. So(column[18].(time.Time), ShouldEqual, dt2)
  145. So(column[19].(time.Time), ShouldEqual, dt.Truncate(time.Minute))
  146. So(column[20].(time.Time), ShouldEqual, dt.Truncate(24*time.Hour))
  147. So(column[21].(time.Time), ShouldEqual, time.Date(1, 1, 1, dt.Hour(), dt.Minute(), dt.Second(), dt.Nanosecond(), time.UTC))
  148. So(column[22].(time.Time), ShouldEqual, dt2.In(time.FixedZone("UTC", int(-7*time.Hour))))
  149. })
  150. Convey("stored procedure", func() {
  151. sql := `
  152. create procedure dbo.test_sp as
  153. begin
  154. select 1
  155. end
  156. `
  157. sess.Exec(sql)
  158. sql = `
  159. ALTER PROCEDURE dbo.test_sp
  160. @from int,
  161. @to int
  162. AS
  163. BEGIN
  164. select
  165. GETDATE() AS Time,
  166. 1 as value,
  167. 'metric' as metric
  168. END
  169. `
  170. _, err := sess.Exec(sql)
  171. So(err, ShouldBeNil)
  172. sql = `
  173. EXEC dbo.test_sp 1, 2
  174. `
  175. _, err = sess.Exec(sql)
  176. So(err, ShouldBeNil)
  177. })
  178. })
  179. }
  180. func InitMSSQLTestDB(t *testing.T) *xorm.Engine {
  181. x, err := xorm.NewEngine(sqlutil.TestDB_Mssql.DriverName, strings.Replace(sqlutil.TestDB_Mssql.ConnStr, "localhost", serverIP, 1))
  182. // x.ShowSQL()
  183. if err != nil {
  184. t.Fatalf("Failed to init mssql db %v", err)
  185. }
  186. sqlutil.CleanDB(x)
  187. return x
  188. }
  189. func genTimeRangeByInterval(from time.Time, duration time.Duration, interval time.Duration) []time.Time {
  190. durationSec := int64(duration.Seconds())
  191. intervalSec := int64(interval.Seconds())
  192. timeRange := []time.Time{}
  193. for i := int64(0); i <= durationSec; i += intervalSec {
  194. timeRange = append(timeRange, from)
  195. from = from.Add(time.Duration(int64(time.Second) * intervalSec))
  196. }
  197. return timeRange
  198. }