mssql.go 9.2 KB

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