mssql.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package mssql
  2. import (
  3. "container/list"
  4. "context"
  5. "database/sql"
  6. "fmt"
  7. "strings"
  8. "time"
  9. _ "github.com/denisenkom/go-mssqldb"
  10. "github.com/go-xorm/core"
  11. "github.com/grafana/grafana/pkg/components/null"
  12. "github.com/grafana/grafana/pkg/log"
  13. "github.com/grafana/grafana/pkg/models"
  14. "github.com/grafana/grafana/pkg/tsdb"
  15. "math"
  16. )
  17. type MssqlQueryEndpoint struct {
  18. sqlEngine tsdb.SqlEngine
  19. log log.Logger
  20. }
  21. func init() {
  22. tsdb.RegisterTsdbQueryEndpoint("mssql", NewMssqlQueryEndpoint)
  23. }
  24. func NewMssqlQueryEndpoint(datasource *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  25. endpoint := &MssqlQueryEndpoint{
  26. log: log.New("tsdb.mssql"),
  27. }
  28. endpoint.sqlEngine = &tsdb.DefaultSqlEngine{
  29. MacroEngine: NewMssqlMacroEngine(),
  30. }
  31. serport := datasource.Url
  32. // fix me: need to have a default port if user did not provide. i.e. 1433
  33. words := strings.Split(serport, ":")
  34. server, port := words[0], words[1]
  35. cnnstr := fmt.Sprintf("server=%s;port=%s;database=%s;user id=%s;password=%s;",
  36. server,
  37. port,
  38. datasource.Database,
  39. datasource.User,
  40. datasource.Password,
  41. )
  42. endpoint.log.Debug("getEngine", "connection", cnnstr)
  43. if err := endpoint.sqlEngine.InitEngine("mssql", datasource, cnnstr); err != nil {
  44. return nil, err
  45. }
  46. return endpoint, nil
  47. }
  48. // Query is the main function for the MssqlExecutor
  49. func (e *MssqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *tsdb.TsdbQuery) (*tsdb.Response, error) {
  50. return e.sqlEngine.Query(ctx, dsInfo, tsdbQuery, e.transformToTimeSeries, e.transformToTable)
  51. }
  52. func (e MssqlQueryEndpoint) transformToTable(query *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult, tsdbQuery *tsdb.TsdbQuery) error {
  53. columnNames, err := rows.Columns()
  54. columnCount := len(columnNames)
  55. if err != nil {
  56. return err
  57. }
  58. rowLimit := 1000000
  59. rowCount := 0
  60. timeIndex := -1
  61. table := &tsdb.Table{
  62. Columns: make([]tsdb.TableColumn, columnCount),
  63. Rows: make([]tsdb.RowValues, 0),
  64. }
  65. for i, name := range columnNames {
  66. table.Columns[i].Text = name
  67. // check if there is a column named time
  68. switch name {
  69. case "time":
  70. timeIndex = i
  71. }
  72. }
  73. columnTypes, err := rows.ColumnTypes()
  74. if err != nil {
  75. return err
  76. }
  77. for ; rows.Next(); rowCount++ {
  78. if rowCount > rowLimit {
  79. return fmt.Errorf("MsSQL query row limit exceeded, limit %d", rowLimit)
  80. }
  81. values, err := e.getTypedRowData(columnTypes, rows)
  82. if err != nil {
  83. return err
  84. }
  85. // convert column named time to unix timestamp to make
  86. // native datetime mssql types work in annotation queries
  87. if timeIndex != -1 {
  88. switch value := values[timeIndex].(type) {
  89. case time.Time:
  90. values[timeIndex] = float64(value.Unix())
  91. }
  92. }
  93. table.Rows = append(table.Rows, values)
  94. }
  95. result.Tables = append(result.Tables, table)
  96. result.Meta.Set("rowCount", rowCount)
  97. return nil
  98. }
  99. func (e MssqlQueryEndpoint) getTypedRowData(types []*sql.ColumnType, rows *core.Rows) (tsdb.RowValues, error) {
  100. values := make([]interface{}, len(types))
  101. valuePtrs := make([]interface{}, len(types))
  102. for i, stype := range types {
  103. e.log.Debug("type", "type", stype)
  104. valuePtrs[i] = &values[i]
  105. }
  106. if err := rows.Scan(valuePtrs...); err != nil {
  107. return nil, err
  108. }
  109. return values, nil
  110. }
  111. func (e MssqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult, tsdbQuery *tsdb.TsdbQuery) error {
  112. pointsBySeries := make(map[string]*tsdb.TimeSeries)
  113. seriesByQueryOrder := list.New()
  114. columnNames, err := rows.Columns()
  115. if err != nil {
  116. return err
  117. }
  118. columnTypes, err := rows.ColumnTypes()
  119. if err != nil {
  120. return err
  121. }
  122. rowLimit := 1000000
  123. rowCount := 0
  124. timeIndex := -1
  125. metricIndex := -1
  126. // check columns of resultset: a column named time is mandatory
  127. // the first text column is treated as metric name unless a column named metric is present
  128. for i, col := range columnNames {
  129. switch col {
  130. case "time":
  131. timeIndex = i
  132. case "metric":
  133. metricIndex = i
  134. default:
  135. if metricIndex == -1 {
  136. switch columnTypes[i].DatabaseTypeName() {
  137. case "VARCHAR", "CHAR", "NVARCHAR", "NCHAR":
  138. metricIndex = i
  139. }
  140. }
  141. }
  142. }
  143. if timeIndex == -1 {
  144. return fmt.Errorf("Found no column named time")
  145. }
  146. fillMissing := query.Model.Get("fill").MustBool(false)
  147. var fillInterval float64
  148. fillValue := null.Float{}
  149. if fillMissing {
  150. fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
  151. if query.Model.Get("fillNull").MustBool(false) == false {
  152. fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
  153. fillValue.Valid = true
  154. }
  155. }
  156. for rows.Next() {
  157. var timestamp float64
  158. var value null.Float
  159. var metricColVal string
  160. var metric string
  161. if rowCount > rowLimit {
  162. return fmt.Errorf("MSSQL query row limit exceeded, limit %d", rowLimit)
  163. }
  164. values, err := e.getTypedRowData(columnTypes, rows)
  165. if err != nil {
  166. return err
  167. }
  168. switch columnValue := values[timeIndex].(type) {
  169. case int64:
  170. timestamp = float64(columnValue * 1000)
  171. case float64:
  172. timestamp = columnValue * 1000
  173. case time.Time:
  174. timestamp = (float64(columnValue.Unix()) * 1000) + float64(columnValue.Nanosecond()/1e6) // in case someone is trying to map times beyond 2262 :D
  175. default:
  176. return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp")
  177. }
  178. if metricIndex >= 0 {
  179. if columnValue, ok := values[metricIndex].(string); ok == true {
  180. metricColVal = columnValue
  181. } else {
  182. return fmt.Errorf("Column metric must be of type CHAR, VARCHAR, NCHAR or NVARCHAR. metric column name: %s type: %s but datatype is %T", columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])
  183. }
  184. }
  185. for i, col := range columnNames {
  186. if i == timeIndex || i == metricIndex {
  187. continue
  188. }
  189. switch columnValue := values[i].(type) {
  190. case int64:
  191. value = null.FloatFrom(float64(columnValue))
  192. case float64:
  193. value = null.FloatFrom(columnValue)
  194. case nil:
  195. value.Valid = false
  196. default:
  197. return fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", col, columnValue, columnValue)
  198. }
  199. // construct the metric name
  200. // if there is more than 3 columns (more than one value) and there is
  201. // a metric column, join them to make the metric name
  202. if metricIndex == -1 {
  203. metric = col
  204. } else if len(columnNames) > 3 {
  205. metric = metricColVal + " - " + col
  206. } else {
  207. metric = metricColVal
  208. }
  209. series, exist := pointsBySeries[metric]
  210. if exist == false {
  211. series = &tsdb.TimeSeries{Name: metric}
  212. pointsBySeries[metric] = series
  213. seriesByQueryOrder.PushBack(metric)
  214. }
  215. if fillMissing {
  216. var intervalStart float64
  217. if exist == false {
  218. intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
  219. } else {
  220. intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
  221. }
  222. // align interval start
  223. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  224. for i := intervalStart; i < timestamp; i += fillInterval {
  225. series.Points = append(series.Points, tsdb.TimePoint{fillValue, null.FloatFrom(i)})
  226. rowCount++
  227. }
  228. }
  229. e.appendTimePoint(pointsBySeries, seriesByQueryOrder, metric, timestamp, value)
  230. rowCount++
  231. }
  232. }
  233. for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
  234. key := elem.Value.(string)
  235. result.Series = append(result.Series, pointsBySeries[key])
  236. if fillMissing {
  237. series := pointsBySeries[key]
  238. // fill in values from last fetched value till interval end
  239. intervalStart := series.Points[len(series.Points)-1][1].Float64
  240. intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
  241. // align interval start
  242. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  243. for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
  244. series.Points = append(series.Points, tsdb.TimePoint{fillValue, null.FloatFrom(i)})
  245. rowCount++
  246. }
  247. }
  248. }
  249. result.Meta.Set("rowCount", rowCount)
  250. return nil
  251. }
  252. // TODO: look at this, specific to the MS SQL datasource. REMOVE?
  253. func (e MssqlQueryEndpoint) appendTimePoint(pointsBySeries map[string]*tsdb.TimeSeries, seriesByQueryOrder *list.List, metric string, timestamp float64, value null.Float) {
  254. if series, exist := pointsBySeries[metric]; exist {
  255. series.Points = append(series.Points, tsdb.TimePoint{value, null.FloatFrom(timestamp)})
  256. } else {
  257. series := &tsdb.TimeSeries{Name: metric}
  258. series.Points = append(series.Points, tsdb.TimePoint{value, null.FloatFrom(timestamp)})
  259. pointsBySeries[metric] = series
  260. seriesByQueryOrder.PushBack(metric)
  261. }
  262. e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
  263. }