relationize 0.0.1

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: 07f7ffbde936c2f83c3b79ce5f68cf2e0edb52d2
4
+ data.tar.gz: 1d3229ecbd96fd5f434d0516ee250aca286cae04
5
+ SHA512:
6
+ metadata.gz: 46fd2f2519ddd1ae60c099b20c9929ada3fa6aec5533a0c53fabea611bba254e2595b8b7b7893c975e92d63bf7e4e8b6c0428bc3a36dac37c6a87055bcf29fcc
7
+ data.tar.gz: 9748eb06f27f2a6b24b3313f9b188ea16d2b4ab9a6a39d4a60d978a2243f0169549f6898c5a2c4ba25df685d4f6038fb5869ac19c751ca9fdeffbc9e5ea3f79a
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
+ /relationize-*\.gem
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in relationize.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Shinta Koyanagi
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # Relationize
2
+
3
+ This gem convert Array to String of SQL relation.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'relationize'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install relationize
20
+
21
+ ## Usage
22
+
23
+ ```ruby
24
+ using Relationize
25
+
26
+ array = [[1, 2], [4, 5]]
27
+
28
+ puts array.to_relation(schema: { a: nil, b: :decimal })
29
+ #=> SELECT "a"::INT8, "b"::DECIMAL FROM (VALUES('1', '2'), ('4', '5')) AS "_t"("a", "b")
30
+
31
+ puts array.to_relation(schema: { a: nil, b: nil }, db: :bq)
32
+ #=> SELECT * FROM (SELECT * FROM (SELECT INTEGER('1') AS a, INTEGER('2') AS b), (SELECT INTEGER('4') AS a, INTEGER('5') AS b)) AS _t
33
+
34
+ puts [["'a'"]].to_relation(schema: { a: nil })
35
+ #=> SELECT "a"::TEXT FROM (VALUES('''a''')) AS "_t"("a")
36
+ ```
37
+
38
+ ### PostgreSQL
39
+
40
+ ```ruby
41
+ require 'relationize'
42
+
43
+ class Hoge
44
+ using Relationize
45
+
46
+ def initialize(data, schema)
47
+ @data = data
48
+ @schema = schema
49
+ end
50
+
51
+ def to_sql
52
+ @data.to_relation(schema: @schema)
53
+ end
54
+ end
55
+
56
+ require 'pg'
57
+
58
+ hoge = Hoge.new(
59
+ [[1, 2, 3], [4, 5, 6]],
60
+ {a: nil, b: nil, c: :decimal}
61
+ )
62
+
63
+ p PG.connect.exec(hoge.to_sql).to_a
64
+ #=> [{"a"=>"1", "b"=>"2", "c"=>"3"}, {"a"=>"4", "b"=>"5", "c"=>"6"}]
65
+
66
+ p PG.connect.exec(<<-SQL).to_a #=> [{"a"=>"1", "b"=>"2", "c"=>"3"}]
67
+ SELECT * FROM (#{hoge.to_sql}) AS t WHERE "a" < 3
68
+ SQL
69
+
70
+ p PG.connect.exec(<<-SQL).to_a #=> [{"a"=>"4", "b"=>"5", "c"=>"6"}]
71
+ WITH t AS (#{hoge.to_sql})
72
+ SELECT * FROM t WHERE t."a" > 3
73
+ SQL
74
+ ```
75
+
76
+ ## Development
77
+
78
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
79
+
80
+ 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).
81
+
82
+ ## Contributing
83
+
84
+ Bug reports and pull requests are welcome on GitHub at https://github.com/yancya/relationize.
85
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "relationize"
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
@@ -0,0 +1,49 @@
1
+ require_relative './relationizer'
2
+ require 'date'
3
+ require 'bigdecimal'
4
+
5
+ module Relationize
6
+ class BqRelationizer < Relationizer
7
+ BQ_TS_FMT = "%Y-%m-%d %H:%M:%S %:z"
8
+
9
+ DEFAULT_TYPES = {
10
+ Integer => :integer,
11
+ Fixnum => :integer,
12
+ Bignum => :integer,
13
+ BigDecimal => :integer,
14
+ Float => :float,
15
+ String => :string,
16
+ TrueClass => :boolean,
17
+ FalseClass => :boolean,
18
+ Date => :string,
19
+ Time => :timestamp
20
+ }
21
+
22
+ def self.to_text_literal(obj)
23
+ obj.nil? ? 'NULL' : obj.to_s.gsub(/'/, "\\'").tap { |s| break "'#{s}'" }
24
+ end
25
+
26
+ def self.to_timestamp_string(obj)
27
+ to_text_literal(obj.is_a?(Time) ? obj.strftime(BQ_TS_FMT) : obj)
28
+ end
29
+
30
+ CAST = {
31
+ "INTEGER" => -> (val, col) { "INTEGER(#{to_text_literal(val)}) AS #{col}"},
32
+ "FLOAT" => -> (val, col) { "FLOAT(#{to_text_literal(val)}) AS #{col}" },
33
+ "BOOLEAN" => -> (val, col) { "BOOLEAN(#{val.nil? ? 'NULL' : (val ? 1 : 0)}) AS #{col}" },
34
+ "STRING" => -> (val, col) { "STRING(#{to_text_literal(val)}) AS #{col}"},
35
+ "TIMESTAMP" => -> (val, col) { "TIMESTAMP(#{to_timestamp_string(val)}) AS #{col}"}
36
+ }
37
+
38
+ def to_s
39
+ rows = @tuples.map { |tuple|
40
+ "(SELECT #{tuple.zip(@columns).zip(oriented_types).map(&method(:to_row)).join(', ')})"
41
+ }.join(', ')
42
+ "SELECT * FROM (SELECT * FROM #{rows}) AS #{@name}"
43
+ end
44
+
45
+ def to_row(((val, col), type))
46
+ CAST[type][val, col]
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,36 @@
1
+ require_relative './relationizer'
2
+ require 'bigdecimal'
3
+ require 'date'
4
+
5
+ module Relationize
6
+ class PgRelationizer < Relationizer
7
+ DEFAULT_TYPES = {
8
+ Integer => :int8,
9
+ Fixnum => :int8,
10
+ Bignum => :decimal,
11
+ BigDecimal => :decimal,
12
+ Float => :float8,
13
+ String => :text,
14
+ TrueClass => :boolean,
15
+ FalseClass => :boolean,
16
+ Date => :date,
17
+ Time => :timestamptz
18
+ }
19
+
20
+ def to_s
21
+ types = oriented_types
22
+ columns = @columns.map(&method(:identifer_quote))
23
+ tuples = @tuples.map { |tuple| "(#{tuple.map { |v| to_text_literal(v) }.join(', ')})"}.join(", ")
24
+ expressions = columns.zip(types).map { |(col, type)| "#{col}::#{type}" }.join(', ')
25
+ "SELECT #{expressions} FROM (VALUES#{tuples}) AS #{identifer_quote(@name)}(#{columns.join(', ')})"
26
+ end
27
+
28
+ private
29
+
30
+ def to_text_literal(obj)
31
+ obj.to_s.gsub(/'/, "''").tap do |s|
32
+ break "'#{s}'"
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,45 @@
1
+ module Relationize
2
+ #
3
+ # Relationizer Base Class
4
+ #
5
+ class Relationizer
6
+ class InvalidElementError < StandardError; end
7
+ class InvalidSchemaError < StandardError; end
8
+ class ReasonlessTypeError < StandardError; end
9
+
10
+ #
11
+ # @param [Array] tuples: Expected to two dimentional Array. For example `[[1, 2], [3, 4]]`
12
+ # @param [Hash] schema: For example `{ id: :integer, amount: :integer}`
13
+ # @param [String] name: Relation name
14
+ #
15
+ def initialize(tuples, schema, name)
16
+ unless tuples.all? { |o| o.is_a?(Array) }
17
+ raise InvalidElementError.new("Element should be Array")
18
+ end
19
+
20
+ unless tuples.map(&:length).all? { |length| length == schema.length }
21
+ raise InvalidSchemaError.new("Tuple size is expected #{schema.length}.")
22
+ end
23
+
24
+ @tuples, @name, @columns, @types = tuples, name, schema.keys, schema.values
25
+ end
26
+
27
+ private
28
+
29
+ def identifer_quote(w)
30
+ %Q{"#{w.to_s.gsub(/"/, '""')}"}
31
+ end
32
+
33
+ def oriented_types
34
+ @tuples.transpose.zip(@types).map do |(values, type)|
35
+ next type.to_s.upcase if type
36
+
37
+ values.map(&:class).uniq.
38
+ map { |klass| self.class::DEFAULT_TYPES[klass] }.compact.uniq.
39
+ tap { |types| raise ReasonlessTypeError.new("Many candidate: #{types.join(', ')}") unless types.one? }.
40
+ tap { |types| raise ReasonlessTypeError.new("Candidate nothing") if types.empty? }.
41
+ first.to_s.upcase
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,3 @@
1
+ module Relationize
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,20 @@
1
+ require_relative 'relationize/version'
2
+
3
+ require_relative 'relationize/pg_relationizer'
4
+ require_relative 'relationize/bq_relationizer'
5
+
6
+ module Relationize
7
+ PG = :pg
8
+ BQ = :bq
9
+
10
+ RELATIONIZERS = {
11
+ PG => PgRelationizer,
12
+ BQ => BqRelationizer
13
+ }
14
+
15
+ refine Array do
16
+ def to_relation(db: PG, schema:, name: '_t')
17
+ RELATIONIZERS[db].new(self, schema, name).to_s
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'relationize/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "relationize"
8
+ spec.version = Relationize::VERSION
9
+ spec.licenses = ['MIT']
10
+ spec.authors = ["yancya"]
11
+ spec.email = ["yancya@upec.jp"]
12
+
13
+ spec.summary = %q{We need evaluable string as relation in RDB}
14
+ spec.description = %q{This gem generate evaluable string as relation in RDB}
15
+ spec.homepage = "https://github.com/yancya/relationize"
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_development_dependency "bundler", "~> 1.11"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ spec.add_development_dependency "minitest", "~> 5.0"
25
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: relationize
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - yancya
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-03-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.11'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.11'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ description: This gem generate evaluable string as relation in RDB
56
+ email:
57
+ - yancya@upec.jp
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - Gemfile
64
+ - LICENSE
65
+ - README.md
66
+ - Rakefile
67
+ - bin/console
68
+ - bin/setup
69
+ - lib/relationize.rb
70
+ - lib/relationize/bq_relationizer.rb
71
+ - lib/relationize/pg_relationizer.rb
72
+ - lib/relationize/relationizer.rb
73
+ - lib/relationize/version.rb
74
+ - relationize.gemspec
75
+ homepage: https://github.com/yancya/relationize
76
+ licenses:
77
+ - MIT
78
+ metadata: {}
79
+ post_install_message:
80
+ rdoc_options: []
81
+ require_paths:
82
+ - lib
83
+ required_ruby_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ required_rubygems_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: '0'
93
+ requirements: []
94
+ rubyforge_project:
95
+ rubygems_version: 2.5.1
96
+ signing_key:
97
+ specification_version: 4
98
+ summary: We need evaluable string as relation in RDB
99
+ test_files: []
100
+ has_rdoc: