mssql.go 6.8 KB

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