db_client.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package sqlqueryreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/sqlqueryreceiver"
  4. import (
  5. "context"
  6. // register db drivers
  7. _ "github.com/SAP/go-hdb/driver"
  8. _ "github.com/denisenkom/go-mssqldb"
  9. _ "github.com/go-sql-driver/mysql"
  10. _ "github.com/lib/pq"
  11. _ "github.com/sijms/go-ora/v2"
  12. _ "github.com/snowflakedb/gosnowflake"
  13. "go.uber.org/multierr"
  14. "go.uber.org/zap"
  15. )
  16. type stringMap map[string]string
  17. type dbClient interface {
  18. queryRows(ctx context.Context, args ...any) ([]stringMap, error)
  19. }
  20. type dbSQLClient struct {
  21. db db
  22. logger *zap.Logger
  23. sql string
  24. }
  25. func newDbClient(db db, sql string, logger *zap.Logger) dbClient {
  26. return dbSQLClient{
  27. db: db,
  28. sql: sql,
  29. logger: logger,
  30. }
  31. }
  32. func (cl dbSQLClient) queryRows(ctx context.Context, args ...any) ([]stringMap, error) {
  33. sqlRows, err := cl.db.QueryContext(ctx, cl.sql, args...)
  34. if err != nil {
  35. return nil, err
  36. }
  37. var out []stringMap
  38. colTypes, err := sqlRows.ColumnTypes()
  39. if err != nil {
  40. return nil, err
  41. }
  42. scanner := newRowScanner(colTypes)
  43. var warnings error
  44. for sqlRows.Next() {
  45. err = scanner.scan(sqlRows)
  46. if err != nil {
  47. return nil, err
  48. }
  49. sm, scanErr := scanner.toStringMap()
  50. if scanErr != nil {
  51. warnings = multierr.Append(warnings, scanErr)
  52. }
  53. out = append(out, sm)
  54. }
  55. return out, warnings
  56. }