Class: BqQuery::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/bq_query/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Client

Returns a new instance of Client.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bq_query/client.rb', line 5

def initialize(opts)
  @client = ::Google::Apis::BigqueryV2::BigqueryService.new

  @client.client_options.application_name = 'BigQuery ruby app'
  @client.client_options.application_version = BqQuery::VERSION

  scope = 'https://www.googleapis.com/auth/bigquery'
  if opts['json_key'].is_a?(String) && !opts['json_key'].empty?
    if File.exist?(opts['json_key'])
      auth = File.open(opts['json_key']) do |f|
        ::Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: f, scope: scope)
      end
    else
      key = StringIO.new(opts['json_key'])
      auth = ::Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: key, scope: scope)
    end
  else
    begin
      key = ::Google::APIClient::KeyUtils.load_from_pkcs12(opts['key'], 'notasecret')
    rescue ArgumentError
      key = ::Google::APIClient::KeyUtils.load_from_pem(opts['key'], 'notasecret')
    end
    auth = Signet::OAuth2::Client.new(
        token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
        audience: 'https://accounts.google.com/o/oauth2/token',
        scope: scope,
        issuer: opts['service_email'],
        signing_key: key)
  end

  @client.authorization = auth

  refresh_auth

  @project_id = opts['project_id']
  @dataset = opts['dataset']
end

Instance Attribute Details

#datasetObject

Returns the value of attribute dataset.



3
4
5
# File 'lib/bq_query/client.rb', line 3

def dataset
  @dataset
end

#project_idObject

Returns the value of attribute project_id.



3
4
5
# File 'lib/bq_query/client.rb', line 3

def project_id
  @project_id
end

Instance Method Details

#refresh_authObject



43
44
45
# File 'lib/bq_query/client.rb', line 43

def refresh_auth
  @client.authorization.fetch_access_token!
end

#sql(given_query, options = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/bq_query/client.rb', line 47

def sql(given_query, options={})
  query_request = ::Google::Apis::BigqueryV2::QueryRequest.new(
    query: given_query,
  )
  query_request.timeout_ms       = options[:timeout] || options[:timeoutMs] || 90 * 1000
  query_request.max_results      = options[:maxResults] if options[:maxResults]
  query_request.dry_run          = options[:dryRun] if options.has_key?(:dryRun)
  query_request.use_query_cache  = options[:useQueryCache] if options.has_key?(:useQueryCache)

  api(
    @client.query_job(
      @project_id,
      query_request
    )
  )
end