Skip to content

Instantly share code, notes, and snippets.

@pedromg
Created October 18, 2013 03:08
Show Gist options
  • Save pedromg/7035908 to your computer and use it in GitHub Desktop.
Save pedromg/7035908 to your computer and use it in GitHub Desktop.
Google API Ruby client, when used for Google BigQuery returns unnamed columns. This new_row_format method solves that, rebuilding the array of hashes with named keys.
def query(sql)
sql += ';' unless sql.end_with?(';')
# api call
res = @bq_client.execute(
:api_method => @bg_api.jobs.query,
:body_object => { "query" => sql },
:timeoutMs => BQ_TIMEOUT,
:parameters => { "projectId" => BQ_EPF_PROJECT_ID }
)
# return result
res
end
def request(sql)
call = query(sql)
if call.response.status.to_i == 200
parsed = jsonify_bigquery_response(call.response.body)
rows = ((parsed['totalRows'].to_i > 0) ? new_row_format(parsed['schema']['fields'], parsed['rows']) : [])
{:size => parsed['totalRows'].to_i , :data => rows, :error => nil}.to_json
else
{:size => 0, :data => nil, :error => 1}.to_json
end
end
def new_row_format(fields, rows)
res = []
rows.each {|r|
h = {}
(0..fields.count-1).each {|fi|
h.merge!({fields[fi]['name'] => r['f'][fi]['v']})
}
res << h
}
res
end
def jsonify_bigquery_response(data)
JSON.parse(data)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment