activerecord_pg_stuff 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: 98e0fe7a1df9305832a41d308d6aba130aec4fb1
4
+ data.tar.gz: 8b5558b5366becdfb1fe1ec0ff77f312ab048e42
5
+ SHA512:
6
+ metadata.gz: 8e20d0174e3ae5d40106b3453807871e7433c02bfdc92dcf25ccf8bfb80fd9fe5a2300053081eb1951d4013a2d91682e1823c25ff1e0597be37318b9957af228
7
+ data.tar.gz: bd22ac3135004e020aeec70bbc4ada73170473dbf790fe6a8d223688d5c36e6f7d9113961871f41ae6dc819eb4fc8c22b9f69e6d20a09747b905c184fb9cd909
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --color
2
+ -fd
3
+ --order=rand
data/.travis.yml ADDED
@@ -0,0 +1,9 @@
1
+ rvm:
2
+ - 1.9.3
3
+ - 2.0.0
4
+
5
+ env:
6
+ global:
7
+ - DATABASE_URL=postgresql://postgres@localhost
8
+
9
+ script: bundle exec rake
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in activerecord_pg_stuff.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Dmitry Galinsky
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # ActiveRecordPgStuff
2
+
3
+ Adds support for working with temporary tables and pivot tables (PostgreSQL only).
4
+
5
+ * [![Build Status](https://travis-ci.org/dima-exe/activerecord_pg_stuff.png?branch=master)](https://travis-ci.org/dima-exe/activerecord_pg_stuff)
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ gem 'activerecord_pg_stuff'
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install activerecord_pg_stuff
20
+
21
+ ## Usage
22
+
23
+ #### Temporary tables
24
+
25
+ Example:
26
+
27
+ User.select(:id, :email).temporary_table do |rel|
28
+ rel.pluck(:id)
29
+ end
30
+
31
+ #### Pivot tables
32
+
33
+ Before using, you need to create the extension:
34
+
35
+ CREATE EXTENSION tablefunc
36
+
37
+ Example:
38
+
39
+ CREATE TABLE payments (id integer, amount integer, seller_id integer, created_at timestamp)
40
+ INSERT INTO payments
41
+ VALUES (1, 1, 1, '2012-10-12 10:00 UTC'),
42
+ (2, 3, 1, '2012-11-12 10:00 UTC'),
43
+ (3, 5, 2, '2012-09-12 10:00 UTC'),
44
+ (4, 7, 2, '2012-10-12 10:00 UTC'),
45
+ (5, 11, 2, '2012-11-12 10:00 UTC'),
46
+ (6, 13, 2, '2012-11-12 10:00 UTC')
47
+
48
+ Payment
49
+ .select("SUM(amount) AS amount", :seller_id, "DATE_TRUNC('month', created_at) AS month")
50
+ .group("seller_id, DATE_TRUNC('month', created_at)")
51
+ .temporary_table do |rel|
52
+ # :month - for row
53
+ # :seller_id - for column
54
+ # :amount - for value
55
+ rel.pivot(:month, :seller_id, :amount)
56
+ end
57
+
58
+ expect(result.headers).to eq [nil, 1, 2]
59
+
60
+ expect(result.rows).to eq [
61
+ [ Time.utc(2012, 9, 1), nil, 5 ],
62
+ [ Time.utc(2012, 10, 1), 1, 7 ],
63
+ [ Time.utc(2012, 11, 1), 3, 24 ],
64
+ ]
65
+
66
+ ## Contributing
67
+
68
+ 1. Fork it
69
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
70
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
71
+ 4. Push to the branch (`git push origin my-new-feature`)
72
+ 5. Create new Pull Request
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]
@@ -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 'activerecord_pg_stuff/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "activerecord_pg_stuff"
8
+ spec.version = ActiveRecordPgStuff::VERSION
9
+ spec.authors = ["Dmitry Galinsky"]
10
+ spec.email = ["dima.exe@gmail.com"]
11
+ spec.description = %q{ Adds support for working with temporary tables and pivot tables (PostgreSQL only) }
12
+ spec.summary = %q{ Adds support for working with temporary tables and pivot tables (PostgreSQL only) }
13
+ spec.homepage = ""
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files`.split($/)
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_runtime_dependency "activerecord", "~> 4.0"
22
+
23
+ spec.add_development_dependency "bundler", "~> 1.3"
24
+ spec.add_development_dependency "rake"
25
+ spec.add_development_dependency "rspec"
26
+ spec.add_development_dependency "pg"
27
+ end
@@ -0,0 +1,12 @@
1
+ require 'active_record'
2
+ require 'active_record/connection_adapters/postgresql_adapter'
3
+
4
+ require File.expand_path("../activerecord_pg_stuff/version", __FILE__)
5
+ require File.expand_path("../activerecord_pg_stuff/connection/temporary_table", __FILE__)
6
+ require File.expand_path("../activerecord_pg_stuff/relation/temporary_table", __FILE__)
7
+ require File.expand_path("../activerecord_pg_stuff/relation/pivot", __FILE__)
8
+
9
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send :include, ActiveRecordPgStuff::Connection::TemporaryTable
10
+
11
+ ActiveRecord::Relation.send :include, ActiveRecordPgStuff::Relation::TemporaryTable
12
+ ActiveRecord::Relation.send :include, ActiveRecordPgStuff::Relation::Pivot
@@ -0,0 +1,22 @@
1
+ module ActiveRecordPgStuff
2
+ module Connection
3
+
4
+ module TemporaryTable
5
+
6
+ def with_temporary_table(name, sql, &block)
7
+ transaction do
8
+ begin
9
+ sql = sql.gsub(/\n/, ' ').gsub(/ +/, ' ').strip
10
+ sql = "CREATE TEMPORARY TABLE #{name} ON COMMIT DROP AS #{sql}"
11
+ conn.execute sql
12
+ yield name
13
+ ensure
14
+ execute("DROP TABLE IF EXISTS #{name}") rescue nil
15
+ end
16
+ end
17
+ end
18
+
19
+ end
20
+
21
+ end
22
+ end
@@ -0,0 +1,54 @@
1
+ module ActiveRecordPgStuff
2
+ module Relation
3
+
4
+ class PivotResult
5
+ attr_reader :headers, :rows
6
+
7
+ def initialize(header_result, result)
8
+ @headers = [nil] + result_to_array(header_result).map(&:first)
9
+ @rows = result_to_array(result)
10
+ end
11
+
12
+ def each_row(&block)
13
+ rows.each(&block)
14
+ end
15
+
16
+ private
17
+ def result_to_array(result)
18
+ result.to_hash.map do |h|
19
+ result.columns.inject([]) do |a, col|
20
+ a << result.column_types[col].type_cast(h[col])
21
+ end
22
+ end
23
+ end
24
+ end
25
+
26
+ module Pivot
27
+
28
+ def pivot(row_id, col_id, val_id)
29
+
30
+ types_sql = %{ SELECT column_name, data_type FROM information_schema.columns WHERE table_name = #{connection.quote self.table_name} AND column_name IN (#{connection.quote row_id},#{connection.quote val_id}) }
31
+ types = connection.select_all types_sql
32
+ types = types.to_a.map(&:values).inject({}) do |a, v|
33
+ a[v[0]] = v[1]
34
+ a
35
+ end
36
+ row_type = types[row_id.to_s]
37
+ val_type = types[val_id.to_s]
38
+
39
+ cols = connection.select_all self.except(:select).select("DISTINCT #{col_id}").order(col_id).to_sql
40
+ cols_list = cols.rows.map(&:first).map do |c|
41
+ "#{col_id}_#{c} #{val_type}"
42
+ end.join(", ")
43
+
44
+ rel_1 = connection.quote self.select(row_id, col_id, val_id).order(row_id).to_sql
45
+ rel_2 = connection.quote self.except(:select).select("DISTINCT #{col_id}").order(col_id).to_sql
46
+ sql = %{ SELECT * FROM crosstab(#{rel_1}, #{rel_2}) AS (row_id #{row_type}, #{cols_list}) }
47
+ PivotResult.new cols, connection.select_all(sql)
48
+ end
49
+
50
+ end
51
+
52
+ end
53
+ end
54
+
@@ -0,0 +1,38 @@
1
+ module ActiveRecordPgStuff
2
+ module Relation
3
+
4
+ module TemporaryTable
5
+
6
+ class Decorator
7
+ attr_reader :table_name, :arel_table, :quoted_table_name
8
+
9
+ def initialize(object, table_name)
10
+ @table_name = table_name
11
+ @object = object
12
+ @arel_table = Arel::Table.new(table_name)
13
+ @quoted_table_name = @object.connection.quote_table_name(table_name)
14
+ end
15
+
16
+ def method_missing(name, *args, &block)
17
+ @object.send(name, *args, &block)
18
+ end
19
+
20
+ def respond_to?(name, *args)
21
+ @object.respond_to?(name, *args)
22
+ end
23
+ end
24
+
25
+ def temporary_table
26
+ tname = "temporary_#{self.table_name}_#{self.object_id}"
27
+ self.klass.connection.with_temporary_table tname, self.to_sql do |name|
28
+ dec = Decorator.new self.klass, name
29
+ rel = ActiveRecord::Relation.new dec, dec.arel_table
30
+ rel.readonly!
31
+ yield rel
32
+ end
33
+ end
34
+
35
+ end
36
+
37
+ end
38
+ end
@@ -0,0 +1,3 @@
1
+ module ActiveRecordPgStuff
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,35 @@
1
+ require 'spec_helper'
2
+
3
+ describe ActiveRecordPgStuff::Connection::TemporaryTable do
4
+
5
+ context "with_temporary_table" do
6
+ let(:sql) { "SELECT * FROM sellers WHERE id IN(1,2)" }
7
+
8
+ it "should create temporary table with 'name' and 'sql' and drop it after block executed" do
9
+ rs = conn.with_temporary_table 'sellers_tmp', sql do |name|
10
+ conn.select_all("SELECT * FROM #{name}").to_a.map(&:values)
11
+ end
12
+ expect(rs).to eq [%w{1 foo}, %w{2 bar}]
13
+ expect {
14
+ conn.execute 'SELECT * FROM sellers_tmp'
15
+ }.to raise_error(ActiveRecord::StatementInvalid, /PG::UndefinedTable/)
16
+ end
17
+
18
+ it "should create nested temporary tables" do
19
+ rs = conn.with_temporary_table 'sellers_tmp', sql do |name|
20
+ sql = "SELECT * FROM #{name} WHERE id = 1"
21
+ conn.with_temporary_table 'sellers_tmp_nested', sql do |name_nested|
22
+ conn.select_all("SELECT * FROM #{name_nested}").to_a.map(&:values)
23
+ end
24
+ end
25
+ expect(rs).to eq [%w{1 foo}]
26
+ expect {
27
+ conn.execute 'SELECT * FROM sellers_tmp'
28
+ }.to raise_error(ActiveRecord::StatementInvalid, /PG::UndefinedTable/)
29
+ expect {
30
+ conn.execute 'SELECT * FROM sellers_tmp_nested'
31
+ }.to raise_error(ActiveRecord::StatementInvalid, /PG::UndefinedTable/)
32
+ end
33
+
34
+ end
35
+ end
@@ -0,0 +1,25 @@
1
+ require 'spec_helper'
2
+
3
+ describe ActiveRecordPgStuff::Relation::TemporaryTable do
4
+
5
+ context "pivot" do
6
+
7
+ let(:rel) { Payment }
8
+
9
+ it "should create pivot table from relation" do
10
+ rs = rel.select(:seller_id, "SUM(amount) AS amount", "DATE_TRUNC('month', created_at) AS created_at")
11
+ .group("seller_id, DATE_TRUNC('month', created_at)").temporary_table do |tmp|
12
+ tmp.pivot :created_at, :seller_id, :amount
13
+ end
14
+
15
+ expect(rs.headers).to eq [nil,1,2]
16
+ expect(rs.rows).to eq [
17
+ [ Time.utc(2012, 9, 1), nil, 5 ],
18
+ [ Time.utc(2012, 10, 1), 1, 7 ],
19
+ [ Time.utc(2012, 11, 1), 3, 24 ],
20
+ ]
21
+ end
22
+
23
+ end
24
+
25
+ end
@@ -0,0 +1,30 @@
1
+ require 'spec_helper'
2
+
3
+ describe ActiveRecordPgStuff::Relation::TemporaryTable do
4
+
5
+ context "temporary_table" do
6
+
7
+ let(:rel) { Seller.where(id: [1,2]) }
8
+
9
+ it "should create temporary table from relation" do
10
+ rs = rel.temporary_table do |tmp|
11
+ tmp.where(id: [1,2]).load
12
+ end
13
+ expect(rs.map(&:class)).to eq [Seller, Seller]
14
+ expect(rs.map(&:class).map(&:table_name)).to eq %w{ sellers sellers }
15
+ expect(rs.map(&:id)).to eq [1,2]
16
+ expect(rs.map(&:readonly?)).to eq [true, true]
17
+ end
18
+
19
+ it "should create nested temporary tables from relation" do
20
+ rs = rel.select("id * 10 AS id").temporary_table do |tmp|
21
+ tmp.where(id: [10]).temporary_table do |nested_tmp|
22
+ nested_tmp.where(id: [10,20]).load
23
+ end
24
+ end
25
+ expect(rs.map(&:id)).to eq [10]
26
+ end
27
+
28
+ end
29
+
30
+ end
@@ -0,0 +1,42 @@
1
+ Bundler.require(:test)
2
+ require 'rspec/autorun'
3
+ require 'logger'
4
+ require File.expand_path("../../lib/activerecord_pg_stuff", __FILE__)
5
+
6
+ ActiveRecord::Base.logger = Logger.new(STDOUT)
7
+
8
+ RSpec.configure do |c|
9
+ c.before(:suite) do
10
+ ActiveRecord::Base.establish_connection
11
+ end
12
+
13
+ c.before(:all) do
14
+ conn.execute 'CREATE EXTENSION IF NOT EXISTS tablefunc'
15
+ conn.execute "CREATE TABLE sellers (id integer, name varchar)"
16
+ conn.execute "INSERT INTO sellers VALUES(1, 'foo'), (2, 'bar'), (3, 'baz')"
17
+
18
+ conn.execute "CREATE TABLE payments (id integer, amount integer, seller_id integer, created_at timestamp)"
19
+ conn.execute "INSERT INTO payments VALUES(1, 1, 1, '2012-10-12 10:00 UTC')"
20
+ conn.execute "INSERT INTO payments VALUES(2, 3, 1, '2012-11-12 10:00 UTC')"
21
+ conn.execute "INSERT INTO payments VALUES(3, 5, 2, '2012-09-12 10:00 UTC')"
22
+ conn.execute "INSERT INTO payments VALUES(4, 7, 2, '2012-10-12 10:00 UTC')"
23
+ conn.execute "INSERT INTO payments VALUES(5, 11, 2, '2012-11-12 10:00 UTC')"
24
+ conn.execute "INSERT INTO payments VALUES(6, 13, 2, '2012-11-12 10:00 UTC')"
25
+ end
26
+
27
+ c.after(:all) do
28
+ conn.execute("DROP TABLE sellers")
29
+ conn.execute("DROP TABLE payments")
30
+ end
31
+ end
32
+
33
+ def conn
34
+ ActiveRecord::Base.connection
35
+ end
36
+
37
+ class Seller < ActiveRecord::Base
38
+ end
39
+
40
+ class Payment < ActiveRecord::Base
41
+ end
42
+
metadata ADDED
@@ -0,0 +1,137 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: activerecord_pg_stuff
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Dmitry Galinsky
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2013-08-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ~>
18
+ - !ruby/object:Gem::Version
19
+ version: '4.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '4.0'
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.3'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ~>
39
+ - !ruby/object:Gem::Version
40
+ version: '1.3'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '>='
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '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: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pg
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - '>='
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - '>='
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: ' Adds support for working with temporary tables and pivot tables (PostgreSQL
84
+ only) '
85
+ email:
86
+ - dima.exe@gmail.com
87
+ executables: []
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - .gitignore
92
+ - .rspec
93
+ - .travis.yml
94
+ - Gemfile
95
+ - LICENSE.txt
96
+ - README.md
97
+ - Rakefile
98
+ - activerecord_pg_stuff.gemspec
99
+ - lib/activerecord_pg_stuff.rb
100
+ - lib/activerecord_pg_stuff/connection/temporary_table.rb
101
+ - lib/activerecord_pg_stuff/relation/pivot.rb
102
+ - lib/activerecord_pg_stuff/relation/temporary_table.rb
103
+ - lib/activerecord_pg_stuff/version.rb
104
+ - spec/lib/connection_temporary_table_spec.rb
105
+ - spec/lib/relation_pivot_spec.rb
106
+ - spec/lib/relation_temporary_table_spec.rb
107
+ - spec/spec_helper.rb
108
+ homepage: ''
109
+ licenses:
110
+ - MIT
111
+ metadata: {}
112
+ post_install_message:
113
+ rdoc_options: []
114
+ require_paths:
115
+ - lib
116
+ required_ruby_version: !ruby/object:Gem::Requirement
117
+ requirements:
118
+ - - '>='
119
+ - !ruby/object:Gem::Version
120
+ version: '0'
121
+ required_rubygems_version: !ruby/object:Gem::Requirement
122
+ requirements:
123
+ - - '>='
124
+ - !ruby/object:Gem::Version
125
+ version: '0'
126
+ requirements: []
127
+ rubyforge_project:
128
+ rubygems_version: 2.0.2
129
+ signing_key:
130
+ specification_version: 4
131
+ summary: Adds support for working with temporary tables and pivot tables (PostgreSQL
132
+ only)
133
+ test_files:
134
+ - spec/lib/connection_temporary_table_spec.rb
135
+ - spec/lib/relation_pivot_spec.rb
136
+ - spec/lib/relation_temporary_table_spec.rb
137
+ - spec/spec_helper.rb