postgres.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package postgres
  2. import (
  3. "container/list"
  4. "context"
  5. "fmt"
  6. "net/url"
  7. "strconv"
  8. "time"
  9. "github.com/go-xorm/core"
  10. "github.com/grafana/grafana/pkg/components/null"
  11. "github.com/grafana/grafana/pkg/log"
  12. "github.com/grafana/grafana/pkg/models"
  13. "github.com/grafana/grafana/pkg/tsdb"
  14. )
  15. type PostgresQueryEndpoint struct {
  16. sqlEngine tsdb.SqlEngine
  17. log log.Logger
  18. }
  19. func init() {
  20. tsdb.RegisterTsdbQueryEndpoint("postgres", NewPostgresQueryEndpoint)
  21. }
  22. func NewPostgresQueryEndpoint(datasource *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  23. endpoint := &PostgresQueryEndpoint{
  24. log: log.New("tsdb.postgres"),
  25. }
  26. endpoint.sqlEngine = &tsdb.DefaultSqlEngine{
  27. MacroEngine: NewPostgresMacroEngine(),
  28. }
  29. cnnstr := generateConnectionString(datasource)
  30. endpoint.log.Debug("getEngine", "connection", cnnstr)
  31. if err := endpoint.sqlEngine.InitEngine("postgres", datasource, cnnstr); err != nil {
  32. return nil, err
  33. }
  34. return endpoint, nil
  35. }
  36. func generateConnectionString(datasource *models.DataSource) string {
  37. password := ""
  38. for key, value := range datasource.SecureJsonData.Decrypt() {
  39. if key == "password" {
  40. password = value
  41. break
  42. }
  43. }
  44. sslmode := datasource.JsonData.Get("sslmode").MustString("verify-full")
  45. return fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", url.PathEscape(datasource.User), url.PathEscape(password), url.PathEscape(datasource.Url), url.PathEscape(datasource.Database), url.QueryEscape(sslmode))
  46. }
  47. func (e *PostgresQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *tsdb.TsdbQuery) (*tsdb.Response, error) {
  48. return e.sqlEngine.Query(ctx, dsInfo, tsdbQuery, e.transformToTimeSeries, e.transformToTable)
  49. }
  50. func (e PostgresQueryEndpoint) transformToTable(query *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult) error {
  51. columnNames, err := rows.Columns()
  52. if err != nil {
  53. return err
  54. }
  55. table := &tsdb.Table{
  56. Columns: make([]tsdb.TableColumn, len(columnNames)),
  57. Rows: make([]tsdb.RowValues, 0),
  58. }
  59. for i, name := range columnNames {
  60. table.Columns[i].Text = name
  61. }
  62. rowLimit := 1000000
  63. rowCount := 0
  64. for ; rows.Next(); rowCount++ {
  65. if rowCount > rowLimit {
  66. return fmt.Errorf("PostgreSQL query row limit exceeded, limit %d", rowLimit)
  67. }
  68. values, err := e.getTypedRowData(rows)
  69. if err != nil {
  70. return err
  71. }
  72. table.Rows = append(table.Rows, values)
  73. }
  74. result.Tables = append(result.Tables, table)
  75. result.Meta.Set("rowCount", rowCount)
  76. return nil
  77. }
  78. func (e PostgresQueryEndpoint) getTypedRowData(rows *core.Rows) (tsdb.RowValues, error) {
  79. types, err := rows.ColumnTypes()
  80. if err != nil {
  81. return nil, err
  82. }
  83. values := make([]interface{}, len(types))
  84. valuePtrs := make([]interface{}, len(types))
  85. for i := 0; i < len(types); i++ {
  86. valuePtrs[i] = &values[i]
  87. }
  88. if err := rows.Scan(valuePtrs...); err != nil {
  89. return nil, err
  90. }
  91. // convert types not handled by lib/pq
  92. // unhandled types are returned as []byte
  93. for i := 0; i < len(types); i++ {
  94. if value, ok := values[i].([]byte); ok == true {
  95. switch types[i].DatabaseTypeName() {
  96. case "NUMERIC":
  97. if v, err := strconv.ParseFloat(string(value), 64); err == nil {
  98. values[i] = v
  99. } else {
  100. e.log.Debug("Rows", "Error converting numeric to float", value)
  101. }
  102. case "UNKNOWN", "CIDR", "INET", "MACADDR":
  103. // char literals have type UNKNOWN
  104. values[i] = string(value)
  105. default:
  106. e.log.Debug("Rows", "Unknown database type", types[i].DatabaseTypeName(), "value", value)
  107. values[i] = string(value)
  108. }
  109. }
  110. }
  111. return values, nil
  112. }
  113. func (e PostgresQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult) error {
  114. pointsBySeries := make(map[string]*tsdb.TimeSeries)
  115. seriesByQueryOrder := list.New()
  116. columnNames, err := rows.Columns()
  117. if err != nil {
  118. return err
  119. }
  120. columnTypes, err := rows.ColumnTypes()
  121. if err != nil {
  122. return err
  123. }
  124. rowLimit := 1000000
  125. rowCount := 0
  126. timeIndex := -1
  127. metricIndex := -1
  128. // check columns of resultset: a column named time is mandatory
  129. // the first text column is treated as metric name unless a column named metric is present
  130. for i, col := range columnNames {
  131. switch col {
  132. case "time":
  133. timeIndex = i
  134. case "metric":
  135. metricIndex = i
  136. default:
  137. if metricIndex == -1 {
  138. switch columnTypes[i].DatabaseTypeName() {
  139. case "UNKNOWN", "TEXT", "VARCHAR", "CHAR":
  140. metricIndex = i
  141. }
  142. }
  143. }
  144. }
  145. if timeIndex == -1 {
  146. return fmt.Errorf("Found no column named time")
  147. }
  148. for rows.Next() {
  149. var timestamp float64
  150. var value null.Float
  151. var metric string
  152. if rowCount > rowLimit {
  153. return fmt.Errorf("PostgreSQL query row limit exceeded, limit %d", rowLimit)
  154. }
  155. values, err := e.getTypedRowData(rows)
  156. if err != nil {
  157. return err
  158. }
  159. switch columnValue := values[timeIndex].(type) {
  160. case int64:
  161. timestamp = float64(columnValue * 1000)
  162. case float64:
  163. timestamp = columnValue * 1000
  164. case time.Time:
  165. timestamp = float64(columnValue.UnixNano() / 1e6)
  166. default:
  167. return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp")
  168. }
  169. if metricIndex >= 0 {
  170. if columnValue, ok := values[metricIndex].(string); ok == true {
  171. metric = columnValue
  172. } else {
  173. return fmt.Errorf("Column metric must be of type char,varchar or text")
  174. }
  175. }
  176. for i, col := range columnNames {
  177. if i == timeIndex || i == metricIndex {
  178. continue
  179. }
  180. switch columnValue := values[i].(type) {
  181. case int64:
  182. value = null.FloatFrom(float64(columnValue))
  183. case float64:
  184. value = null.FloatFrom(columnValue)
  185. case nil:
  186. value.Valid = false
  187. default:
  188. return fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", col, columnValue, columnValue)
  189. }
  190. if metricIndex == -1 {
  191. metric = col
  192. }
  193. e.appendTimePoint(pointsBySeries, seriesByQueryOrder, metric, timestamp, value)
  194. rowCount++
  195. }
  196. }
  197. for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
  198. key := elem.Value.(string)
  199. result.Series = append(result.Series, pointsBySeries[key])
  200. }
  201. result.Meta.Set("rowCount", rowCount)
  202. return nil
  203. }
  204. func (e PostgresQueryEndpoint) appendTimePoint(pointsBySeries map[string]*tsdb.TimeSeries, seriesByQueryOrder *list.List, metric string, timestamp float64, value null.Float) {
  205. if series, exist := pointsBySeries[metric]; exist {
  206. series.Points = append(series.Points, tsdb.TimePoint{value, null.FloatFrom(timestamp)})
  207. } else {
  208. series := &tsdb.TimeSeries{Name: metric}
  209. series.Points = append(series.Points, tsdb.TimePoint{value, null.FloatFrom(timestamp)})
  210. pointsBySeries[metric] = series
  211. seriesByQueryOrder.PushBack(metric)
  212. }
  213. e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
  214. }