bq_query 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 38ec615fda3699fc53a2a9a5d439ba0fe8a41d0c
4
+ data.tar.gz: c0c81c0584e128c8694576f2c2884318d9471123
5
+ SHA512:
6
+ metadata.gz: 3aa542ec95b607ec513482605efdc5e84f5edb8e3431151fcddb0f982b5b690e01fecd6269e8f139191e65907152f7e754bec3ca832db2761e9b007f3ce3e410
7
+ data.tar.gz: 826a638f039eb0405f5917bfcfad97bfd57fbeafddcdad3fe19742876b61ccc0bc7983045ef1c90e6f96495072ad0ac6223d45c49607cefd7fc609a14eec5bae
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ /vendor/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.1
5
+ before_install: gem install bundler -v 1.12.5
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in bq_query.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 YuheiNakasaka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # BqQuery
2
+
3
+ Bigquery client for only executing query
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'bq_query'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install bq_query
20
+
21
+ ## Usage
22
+
23
+ ### Example
24
+
25
+ ```
26
+ require 'bq_query'
27
+
28
+ opts = {}
29
+ opts['service_email'] = '1234@developer.gserviceaccount.com'
30
+ opts['key'] = '/path/to/somekeyfile-privatekey.p12'
31
+ opts['project_id'] = '54321'
32
+ opts['dataset'] = 'yourdataset'
33
+
34
+ bq = BqQuery::Client.new(opts)
35
+
36
+ bq.sql("SELECT * FROM [project:dataset.example_table] LIMIT 100")
37
+ ```
38
+
39
+ ## Development
40
+
41
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
42
+
43
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
44
+
45
+ ## Contributing
46
+
47
+ Bug reports and pull requests are welcome on GitHub at https://github.com/YuheiNakasaka/bq_query.
48
+
49
+
50
+ ## License
51
+
52
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "bq_query"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/bq_query.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'bq_query/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "bq_query"
8
+ spec.version = BqQuery::VERSION
9
+ spec.authors = ["YuheiNakasaka"]
10
+ spec.email = ["yuhei.nakasaka@gmail.com"]
11
+
12
+ spec.summary = %q{Bigquery client for only executing query}
13
+ spec.description = %q{Bigquery client for only executing query}
14
+ spec.homepage = "https://github.com/YuheiNakasaka/bq_query"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_dependency "google-api-client", "~> 0.9.3"
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.12"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3.0"
27
+ end
data/lib/bq_query.rb ADDED
@@ -0,0 +1,14 @@
1
+ require "bq_query/version"
2
+ require "bq_query/client"
3
+ require "bq_query/attribute"
4
+ require "bq_query/attribute/base"
5
+ require "bq_query/attribute/boolean"
6
+ require "bq_query/attribute/float"
7
+ require "bq_query/attribute/integer"
8
+ require "bq_query/attribute/string"
9
+ require "bq_query/attribute/timestamp"
10
+ require "google/apis/bigquery_v2"
11
+ require "google/api_client/auth/key_utils"
12
+
13
+ module BqQuery
14
+ end
@@ -0,0 +1,15 @@
1
+ module BqQuery
2
+ module Attribute
3
+ class UnknownType < StandardError
4
+ end
5
+
6
+ def self.new(name: nil, type: nil, value: nil)
7
+ class_name = (type[0] || '').upcase + (type[1..-1] || '').downcase
8
+ if klass = const_get(class_name)
9
+ klass.new(name, value)
10
+ else
11
+ fail UnknownType, "unknown type: #{type}"
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ module BqQuery
2
+ module Attribute
3
+ class Base
4
+ attr_reader :name, :type, :value
5
+
6
+ def initialize(name, value)
7
+ @name, @value = name, value
8
+ @type = self.class.name.split('::').last.downcase.to_sym
9
+ end
10
+
11
+ def parse
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,13 @@
1
+ module BqQuery
2
+ module Attribute
3
+ class Boolean < Base
4
+ def parse
5
+ case @value
6
+ when nil then nil
7
+ when 'true' then true
8
+ when 'false' then false
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,10 @@
1
+ module BqQuery
2
+ module Attribute
3
+ class Float < Base
4
+ def parse
5
+ return nil if @value.nil?
6
+ @value.to_f
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,10 @@
1
+ module BqQuery
2
+ module Attribute
3
+ class Integer < Base
4
+ def parse
5
+ return nil if @value.nil?
6
+ @value.to_i
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,9 @@
1
+ module BqQuery
2
+ module Attribute
3
+ class String < Base
4
+ def parse
5
+ @value
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,10 @@
1
+ module BqQuery
2
+ module Attribute
3
+ class Timestamp < Base
4
+ def parse
5
+ return nil if @value.nil?
6
+ Time.at(@value.to_f)
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,130 @@
1
+ module BqQuery
2
+ class Client
3
+ attr_accessor :dataset, :project_id
4
+
5
+ def initialize(opts)
6
+ @client = ::Google::Apis::BigqueryV2::BigqueryService.new
7
+
8
+ @client.client_options.application_name = 'BigQuery ruby app'
9
+ @client.client_options.application_version = BqQuery::VERSION
10
+
11
+ scope = 'https://www.googleapis.com/auth/bigquery'
12
+ if opts['json_key'].is_a?(String) && !opts['json_key'].empty?
13
+ if File.exist?(opts['json_key'])
14
+ auth = File.open(opts['json_key']) do |f|
15
+ ::Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: f, scope: scope)
16
+ end
17
+ else
18
+ key = StringIO.new(opts['json_key'])
19
+ auth = ::Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: key, scope: scope)
20
+ end
21
+ else
22
+ begin
23
+ key = ::Google::APIClient::KeyUtils.load_from_pkcs12(opts['key'], 'notasecret')
24
+ rescue ArgumentError
25
+ key = ::Google::APIClient::KeyUtils.load_from_pem(opts['key'], 'notasecret')
26
+ end
27
+ auth = Signet::OAuth2::Client.new(
28
+ token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
29
+ audience: 'https://accounts.google.com/o/oauth2/token',
30
+ scope: scope,
31
+ issuer: opts['service_email'],
32
+ signing_key: key)
33
+ end
34
+
35
+ @client.authorization = auth
36
+
37
+ refresh_auth
38
+
39
+ @project_id = opts['project_id']
40
+ @dataset = opts['dataset']
41
+ end
42
+
43
+ def refresh_auth
44
+ @client.authorization.fetch_access_token!
45
+ end
46
+
47
+ def sql(given_query, options={})
48
+ query_request = ::Google::Apis::BigqueryV2::QueryRequest.new(
49
+ query: given_query,
50
+ )
51
+ query_request.timeout_ms = options[:timeout] || options[:timeoutMs] || 90 * 1000
52
+ query_request.max_results = options[:maxResults] if options[:maxResults]
53
+ query_request.dry_run = options[:dryRun] if options.has_key?(:dryRun)
54
+ query_request.use_query_cache = options[:useQueryCache] if options.has_key?(:useQueryCache)
55
+
56
+ api(
57
+ @client.query_job(
58
+ @project_id,
59
+ query_request
60
+ )
61
+ )
62
+ end
63
+
64
+ private
65
+
66
+ def api(resp)
67
+ data = deep_stringify_keys(resp.to_h)
68
+ handle_error(data) if data && is_error?(data)
69
+ arrange_records(data)
70
+ end
71
+
72
+ def deep_stringify_keys(response)
73
+ convert_key_proc = Proc.new { |k| camel_case_lower(k.to_s) }
74
+ Hash[response.map { |k, v| [convert_key_proc.call(k), process_value(v, convert_key_proc)] }]
75
+ end
76
+
77
+ def camel_case_lower(str)
78
+ str.split('_').inject([]){ |buffer,e| buffer.push(buffer.empty? ? e : e.capitalize) }.join
79
+ end
80
+
81
+ def process_value(val, convert_key_proc)
82
+ case val
83
+ when Hash
84
+ Hash[val.map {|k, v| [convert_key_proc.call(k), process_value(v, convert_key_proc)] }]
85
+ when Array
86
+ val.map{ |v| process_value(v, convert_key_proc) }
87
+ else
88
+ val
89
+ end
90
+ end
91
+
92
+ def arrange_records(response)
93
+ keys = column_names(response)
94
+ types = column_types(response)
95
+ records = extract_records(response)
96
+ records.map do |record|
97
+ vals = record.map.with_index do |v, index|
98
+ Attribute.new(value: v, type: types[index]).parse
99
+ end
100
+ [keys, vals].transpose.to_h
101
+ end
102
+ end
103
+
104
+ def column_names(response)
105
+ response['schema']['fields'].map {|field| field['name'] }
106
+ end
107
+
108
+ def column_types(response)
109
+ response['schema']['fields'].map {|field| field['type'] }
110
+ end
111
+
112
+ def extract_records(response)
113
+ (response['rows'] || []).map {|row| row['f'].map {|record| record['v'] } }
114
+ end
115
+
116
+ def is_error?(response)
117
+ !response["error"].nil?
118
+ end
119
+
120
+ def handle_error(response)
121
+ error = response['error']
122
+ case error['code']
123
+ when 404
124
+ fail BigQuery::Errors::NotFound, error['message']
125
+ else
126
+ fail BigQuery::Errors::BigQueryError, error['message']
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,3 @@
1
+ module BqQuery
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,120 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bq_query
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - YuheiNakasaka
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-05-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: google-api-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.9.3
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.9.3
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.12'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.12'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ description: Bigquery client for only executing query
70
+ email:
71
+ - yuhei.nakasaka@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - ".travis.yml"
79
+ - Gemfile
80
+ - LICENSE.txt
81
+ - README.md
82
+ - Rakefile
83
+ - bin/console
84
+ - bin/setup
85
+ - bq_query.gemspec
86
+ - lib/bq_query.rb
87
+ - lib/bq_query/attribute.rb
88
+ - lib/bq_query/attribute/base.rb
89
+ - lib/bq_query/attribute/boolean.rb
90
+ - lib/bq_query/attribute/float.rb
91
+ - lib/bq_query/attribute/integer.rb
92
+ - lib/bq_query/attribute/string.rb
93
+ - lib/bq_query/attribute/timestamp.rb
94
+ - lib/bq_query/client.rb
95
+ - lib/bq_query/version.rb
96
+ homepage: https://github.com/YuheiNakasaka/bq_query
97
+ licenses:
98
+ - MIT
99
+ metadata: {}
100
+ post_install_message:
101
+ rdoc_options: []
102
+ require_paths:
103
+ - lib
104
+ required_ruby_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ required_rubygems_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubyforge_project:
116
+ rubygems_version: 2.5.1
117
+ signing_key:
118
+ specification_version: 4
119
+ summary: Bigquery client for only executing query
120
+ test_files: []