bigqueryquerier.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package gcp
  2. import (
  3. "context"
  4. "fmt"
  5. "cloud.google.com/go/bigquery"
  6. "github.com/opencost/opencost/pkg/cloud"
  7. )
  8. type BigQueryQuerier struct {
  9. BigQueryConfiguration
  10. ConnectionStatus cloud.ConnectionStatus
  11. }
  12. func (bqq *BigQueryQuerier) GetStatus() cloud.ConnectionStatus {
  13. // initialize status if it has not done so; this can happen if the integration is inactive
  14. if bqq.ConnectionStatus.String() == "" {
  15. bqq.ConnectionStatus = cloud.InitialStatus
  16. }
  17. return bqq.ConnectionStatus
  18. }
  19. func (bqq *BigQueryQuerier) Equals(config cloud.Config) bool {
  20. thatConfig, ok := config.(*BigQueryQuerier)
  21. if !ok {
  22. return false
  23. }
  24. return bqq.BigQueryConfiguration.Equals(&thatConfig.BigQueryConfiguration)
  25. }
  26. func (bqq *BigQueryQuerier) Query(ctx context.Context, queryStr string) (*bigquery.RowIterator, error) {
  27. err := bqq.Validate()
  28. if err != nil {
  29. bqq.ConnectionStatus = cloud.InvalidConfiguration
  30. return nil, err
  31. }
  32. client, err := bqq.GetBigQueryClient(ctx)
  33. if err != nil {
  34. bqq.ConnectionStatus = cloud.FailedConnection
  35. return nil, err
  36. }
  37. query := client.Query(queryStr)
  38. query.Location = client.Location
  39. iter, err := query.Read(ctx)
  40. // If result is empty and connection status is not already successful update status to missing data
  41. if iter == nil && bqq.ConnectionStatus != cloud.SuccessfulConnection {
  42. bqq.ConnectionStatus = cloud.MissingData
  43. } else {
  44. bqq.ConnectionStatus = cloud.SuccessfulConnection
  45. }
  46. if err != nil {
  47. return iter, fmt.Errorf("BigQueryQuerier: Query: error reading query results: %w", err)
  48. }
  49. return iter, nil
  50. }