ancestry_joins 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: 202ddb44a51c5d2f85b2301f8ffdd308b8d9c275
4
+ data.tar.gz: 40957c6db4e124df74a9df71c0071345143a3461
5
+ SHA512:
6
+ metadata.gz: c6b9d34c587a6c8f84fcaa31fecf3b83d4d527954b441a4a85ced4762abeafd47806b4ab9052e87b89d8b3f9716ff9a49abe4fa59ec3d91296f850d04cf9aec3
7
+ data.tar.gz: 47bd49c3c65251ad4b1134032bc3f30b82a8a14c2498359ea9ace055a53fa4c55b5c38616c037721a8f8f0ff361918154f00c9d89559e3983c495808b84a0b0f
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.rubocop.yml ADDED
@@ -0,0 +1,5 @@
1
+ AllCops:
2
+ Include:
3
+ - '**/*.rb'
4
+ Exclude:
5
+ - 'db/**/*'
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.3
5
+ before_install: gem install bundler -v 1.12.5
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in ancestry_joins.gemspec
4
+ gemspec
5
+
6
+ group :development, :test do
7
+ gem 'pry'
8
+ gem 'pg'
9
+ gem 'table_print'
10
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Scott Pierce
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,86 @@
1
+ # AncestryJoins
2
+ This gem provides additional ActiveRecord scopes to fetch ancestry records in
3
+ bulk.
4
+
5
+ ## Problem
6
+ The ancestry gem only provides instance scopes which when used in
7
+ iteration causes N+1 query performance issues.
8
+ For example:
9
+
10
+ ```ruby
11
+ # if we have 100 interesting items, this will run 1 + 100 querys!
12
+ Item.where(interesting: true).flat_map{|i| i.ancestors}
13
+ ```
14
+
15
+ ## Solution
16
+
17
+ Using this gem will fetch identical results to the `flat_map` but in a single
18
+ query.
19
+
20
+ ```ruby
21
+ Item.where(interesting: true).with_ancestors_only
22
+ ```
23
+
24
+ ## Caveats
25
+
26
+ Do to the querying method, only Postgres is supported at the moment.
27
+ More databases can be supported in the future. Look at `lib/ancestry_joins.rb`
28
+ to implement scopes for another database.
29
+
30
+ ## Usage
31
+
32
+ **IMPORTANT** Use the scope *last* in the chain for good performance, otherwise
33
+ the ancestry grouping act on the entire table before applying the filter.
34
+ If you have other models to join against the ancestry, those maybe added after
35
+ including the ancestry joins.
36
+
37
+ ```ruby
38
+ class Item < ActiveRecord::Base
39
+ has_ancestry
40
+ include AncestryJoins
41
+
42
+ has_many :widgets
43
+ end
44
+
45
+ # Get list of Items with red color, their parents regardless of color, and the
46
+ # red items or red items ancestors' parents widgets are blue.
47
+ Item
48
+ .where(color: 'red')
49
+ .with_ancestors
50
+ .joins(:widgets)
51
+ .merge(Widget.where(color: 'blue'))
52
+ ```
53
+
54
+ Look to the specs for more details.
55
+
56
+ ## Installation
57
+
58
+ Add this line to your application's Gemfile:
59
+
60
+ ```ruby
61
+ gem 'ancestry_joins'
62
+ ```
63
+
64
+ And then execute:
65
+
66
+ $ bundle
67
+
68
+ Or install it yourself as:
69
+
70
+ $ gem install ancestry_joins
71
+
72
+ ## Development
73
+
74
+ 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.
75
+
76
+ 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).
77
+
78
+ ## Contributing
79
+
80
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ddrscott/ancestry_joins.
81
+
82
+
83
+ ## License
84
+
85
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
86
+
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 'ancestry_joins/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'ancestry_joins'
8
+ spec.version = AncestryJoins::VERSION
9
+ spec.authors = ['Scott Pierce']
10
+ spec.email = ['scott.pierce@centro.net']
11
+
12
+ spec.summary = 'Provides scopes to join ancestry records in bulk.'
13
+ spec.homepage = "https://github.com/ddrscott/ancestry_joins"
14
+ spec.license = 'MIT'
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
17
+ spec.bindir = 'exe'
18
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
+ spec.require_paths = ['lib']
20
+
21
+ spec.add_development_dependency 'bundler', '~> 1.12'
22
+ spec.add_development_dependency 'rake', '~> 10.0'
23
+ spec.add_development_dependency 'rspec', '~> 3.0'
24
+ spec.add_dependency 'activerecord', '>= 4.0.0'
25
+ spec.add_dependency 'activesupport', '>= 4.0.0'
26
+ spec.add_dependency 'ancestry', '>= 2.1.0'
27
+ end
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "ancestry_joins"
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
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,3 @@
1
+ module AncestryJoins
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,61 @@
1
+ require 'ancestry_joins/version'
2
+ require 'active_record'
3
+ require 'pg'
4
+ require 'ancestry'
5
+ require 'active_support/concern'
6
+
7
+ module AncestryJoins
8
+ extend ActiveSupport::Concern
9
+
10
+ included do
11
+ case connection.adapter_name.downcase.to_sym
12
+ when :postgresql
13
+ # Helper to add all selection fields. This is the default behavior until
14
+ # you add your own selections.
15
+ scope :with_star, -> { select("#{table_name}.*") }
16
+
17
+ # Helper to get the root_id from the ancestry string column.
18
+ scope :with_root_id, -> {
19
+ select("coalesce(nullif(trim(split_part(#{table_name}.#{ancestry_column}, '/', 1)), ''), #{table_name}.#{primary_key}::text) AS ancestry_root_id")
20
+ }
21
+
22
+ # Joins ancestors to the existing scope.
23
+ # It's important to make this the last scope for efficiency.
24
+ # @params [Boolean] include_self will keep the current record in the
25
+ # results. Otherwise, you'll only get the ancestors. `include_self`
26
+ # defaults to `true`
27
+ # @params [Integer] nth limit the results to just the nth child in the
28
+ # ancestry.
29
+ # @params [Integer] nth_reverse opposite of `nth`. Useful for getting the
30
+ # tips of the ancestry.
31
+ scope :with_ancestors, ->(include_self: true, nth: nil, nth_reverse: nil) {
32
+ primary_key_type = columns.detect { |d| d.name == primary_key }.sql_type
33
+
34
+ select_nth_ancestor_id = <<-SQL.squish
35
+ SELECT *, row_number() OVER ()
36
+ FROM unnest(string_to_array(nullif(#{table_name}.#{ancestry_column}, ''), '/')::#{primary_key_type}[] #{include_self ? " || ARRAY[#{table_name}.#{primary_key}]" : nil})
37
+ SQL
38
+
39
+ query = select('ancestors.*')
40
+ .select('rank() OVER (PARTITION BY ancestors.ancestry_root_id ORDER BY ancestor_ids.nth desc nulls last) AS ancestry_nth_reverse')
41
+ .select('ancestor_ids.nth AS ancestry_nth')
42
+ .joins("JOIN LATERAL (#{select_nth_ancestor_id}) AS ancestor_ids(id, nth) ON true")
43
+ .joins("JOIN (#{unscoped.with_star.with_root_id.to_sql}) AS ancestors ON ancestors.#{primary_key} = ancestor_ids.#{primary_key}")
44
+
45
+ query = unscoped.from("(#{query.to_sql}) AS #{table_name}")
46
+
47
+ query = query.where('ancestry_nth = ?', nth) if nth
48
+ query = query.where('ancestry_nth_reverse = ?', nth_reverse) if nth_reverse
49
+ query
50
+ }
51
+
52
+ # Helper to exclude current record from results.
53
+ scope :with_ancestors_only, ->(**options) { with_ancestors(include_self: false, **options) }
54
+
55
+ # Helper to build `nth_reverse: 1`
56
+ scope :with_ancestors_leafs_only, ->(**options) { with_ancestors(nth_reverse: 1, **options) }
57
+ else
58
+ raise NotImplementedError, "Unknown adapter type `#{adapter_type}`"
59
+ end
60
+ end
61
+ end
metadata ADDED
@@ -0,0 +1,141 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ancestry_joins
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Scott Pierce
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-12-16 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.12'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.12'
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: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: activerecord
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 4.0.0
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 4.0.0
69
+ - !ruby/object:Gem::Dependency
70
+ name: activesupport
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 4.0.0
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: 4.0.0
83
+ - !ruby/object:Gem::Dependency
84
+ name: ancestry
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: 2.1.0
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: 2.1.0
97
+ description:
98
+ email:
99
+ - scott.pierce@centro.net
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".rspec"
106
+ - ".rubocop.yml"
107
+ - ".travis.yml"
108
+ - Gemfile
109
+ - LICENSE.txt
110
+ - README.md
111
+ - Rakefile
112
+ - ancestry_joins.gemspec
113
+ - bin/console
114
+ - bin/setup
115
+ - lib/ancestry_joins.rb
116
+ - lib/ancestry_joins/version.rb
117
+ homepage: https://github.com/ddrscott/ancestry_joins
118
+ licenses:
119
+ - MIT
120
+ metadata: {}
121
+ post_install_message:
122
+ rdoc_options: []
123
+ require_paths:
124
+ - lib
125
+ required_ruby_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: '0'
130
+ required_rubygems_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ requirements: []
136
+ rubyforge_project:
137
+ rubygems_version: 2.4.5.1
138
+ signing_key:
139
+ specification_version: 4
140
+ summary: Provides scopes to join ancestry records in bulk.
141
+ test_files: []