active_record-union_relation 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 55af3304374e93713fd47016a6704d6c9f611fbcdb42a4e60bcf2d22695e1eae
4
+ data.tar.gz: 598b2fae9bf45f819a34d32cf25803f99a8b74a5e52a66a201054795a2b7e75f
5
+ SHA512:
6
+ metadata.gz: 9feebe97d475b1cbbfbf5240abfecdc487012a6a40a5c27633cf968a4272c8cc5e471e69b1f0b13e6ed5ead56e24485678168f004497636a0dc3ee24e30a994e
7
+ data.tar.gz: 3681e533de162a792f6c28fe02e8747e35378229687591f97add94f3ce44dc92fbb249721a4a0d0a8077680420929a8dcac59cc52ce21e00f4f7450a285eeead
@@ -0,0 +1,6 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "bundler"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "daily"
@@ -0,0 +1,39 @@
1
+ name: Main
2
+ on: push
3
+ jobs:
4
+ ci:
5
+ name: CI
6
+ runs-on: ubuntu-latest
7
+ env:
8
+ CI: true
9
+ DATABASE_URL: postgres://postgres:@localhost:5432/postgres
10
+ RAILS_ENV: test
11
+ services:
12
+ postgres:
13
+ image: postgres:11.5
14
+ ports:
15
+ - 5432:5432
16
+ options: >-
17
+ --health-cmd pg_isready
18
+ --health-interval 10s
19
+ --health-timeout 5s
20
+ --health-retries 5
21
+ steps:
22
+ - run: sudo apt-get -yqq install libpq-dev
23
+ - uses: actions/checkout@master
24
+ - uses: ruby/setup-ruby@v1
25
+ with:
26
+ ruby-version: 2.7
27
+ - uses: actions/cache@v1
28
+ with:
29
+ path: vendor/bundle
30
+ key: ${{ runner.os }}-gems-${{ hashFiles('**/Gemfile.lock') }}
31
+ restore-keys: |
32
+ ${{ runner.os }}-gems-
33
+ - name: Install deps
34
+ run: |
35
+ bundle config path vendor/bundle
36
+ bundle install --jobs 4 --retry 3
37
+ - name: Lint and test
38
+ run: |
39
+ bundle exec rake test
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
@@ -0,0 +1,10 @@
1
+ pull_request_rules:
2
+ - name: Automatically merge dependencies
3
+ conditions:
4
+ - base=master
5
+ - label=dependencies
6
+ - status-success=CI
7
+ actions:
8
+ merge:
9
+ strict: true
10
+ delete_head_branch: {}
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2020-10-08
10
+
11
+ ### Added
12
+
13
+ - 🎉 Initial release. 🎉
14
+
15
+ [unreleased]: https://github.com/kddeisz/active_record-union_relation/compare/v0.1.0...HEAD
16
+ [0.1.0]: https://github.com/kddeisz/active_record-union_relation/compare/a71bb8...v0.1.0
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at kevin.deisz@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
@@ -0,0 +1,146 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ active_record-union_relation (0.1.0)
5
+ activerecord (>= 6)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ actioncable (6.0.3.4)
11
+ actionpack (= 6.0.3.4)
12
+ nio4r (~> 2.0)
13
+ websocket-driver (>= 0.6.1)
14
+ actionmailbox (6.0.3.4)
15
+ actionpack (= 6.0.3.4)
16
+ activejob (= 6.0.3.4)
17
+ activerecord (= 6.0.3.4)
18
+ activestorage (= 6.0.3.4)
19
+ activesupport (= 6.0.3.4)
20
+ mail (>= 2.7.1)
21
+ actionmailer (6.0.3.4)
22
+ actionpack (= 6.0.3.4)
23
+ actionview (= 6.0.3.4)
24
+ activejob (= 6.0.3.4)
25
+ mail (~> 2.5, >= 2.5.4)
26
+ rails-dom-testing (~> 2.0)
27
+ actionpack (6.0.3.4)
28
+ actionview (= 6.0.3.4)
29
+ activesupport (= 6.0.3.4)
30
+ rack (~> 2.0, >= 2.0.8)
31
+ rack-test (>= 0.6.3)
32
+ rails-dom-testing (~> 2.0)
33
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
34
+ actiontext (6.0.3.4)
35
+ actionpack (= 6.0.3.4)
36
+ activerecord (= 6.0.3.4)
37
+ activestorage (= 6.0.3.4)
38
+ activesupport (= 6.0.3.4)
39
+ nokogiri (>= 1.8.5)
40
+ actionview (6.0.3.4)
41
+ activesupport (= 6.0.3.4)
42
+ builder (~> 3.1)
43
+ erubi (~> 1.4)
44
+ rails-dom-testing (~> 2.0)
45
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
46
+ activejob (6.0.3.4)
47
+ activesupport (= 6.0.3.4)
48
+ globalid (>= 0.3.6)
49
+ activemodel (6.0.3.4)
50
+ activesupport (= 6.0.3.4)
51
+ activerecord (6.0.3.4)
52
+ activemodel (= 6.0.3.4)
53
+ activesupport (= 6.0.3.4)
54
+ activestorage (6.0.3.4)
55
+ actionpack (= 6.0.3.4)
56
+ activejob (= 6.0.3.4)
57
+ activerecord (= 6.0.3.4)
58
+ marcel (~> 0.3.1)
59
+ activesupport (6.0.3.4)
60
+ concurrent-ruby (~> 1.0, >= 1.0.2)
61
+ i18n (>= 0.7, < 2)
62
+ minitest (~> 5.1)
63
+ tzinfo (~> 1.1)
64
+ zeitwerk (~> 2.2, >= 2.2.2)
65
+ builder (3.2.4)
66
+ concurrent-ruby (1.1.7)
67
+ crass (1.0.6)
68
+ erubi (1.9.0)
69
+ globalid (0.4.2)
70
+ activesupport (>= 4.2.0)
71
+ i18n (1.8.5)
72
+ concurrent-ruby (~> 1.0)
73
+ loofah (2.7.0)
74
+ crass (~> 1.0.2)
75
+ nokogiri (>= 1.5.9)
76
+ mail (2.7.1)
77
+ mini_mime (>= 0.1.1)
78
+ marcel (0.3.3)
79
+ mimemagic (~> 0.3.2)
80
+ method_source (1.0.0)
81
+ mimemagic (0.3.5)
82
+ mini_mime (1.0.2)
83
+ mini_portile2 (2.4.0)
84
+ minitest (5.14.2)
85
+ nio4r (2.5.4)
86
+ nokogiri (1.10.10)
87
+ mini_portile2 (~> 2.4.0)
88
+ pg (1.2.3)
89
+ rack (2.2.3)
90
+ rack-test (1.1.0)
91
+ rack (>= 1.0, < 3)
92
+ rails (6.0.3.4)
93
+ actioncable (= 6.0.3.4)
94
+ actionmailbox (= 6.0.3.4)
95
+ actionmailer (= 6.0.3.4)
96
+ actionpack (= 6.0.3.4)
97
+ actiontext (= 6.0.3.4)
98
+ actionview (= 6.0.3.4)
99
+ activejob (= 6.0.3.4)
100
+ activemodel (= 6.0.3.4)
101
+ activerecord (= 6.0.3.4)
102
+ activestorage (= 6.0.3.4)
103
+ activesupport (= 6.0.3.4)
104
+ bundler (>= 1.3.0)
105
+ railties (= 6.0.3.4)
106
+ sprockets-rails (>= 2.0.0)
107
+ rails-dom-testing (2.0.3)
108
+ activesupport (>= 4.2.0)
109
+ nokogiri (>= 1.6)
110
+ rails-html-sanitizer (1.3.0)
111
+ loofah (~> 2.3)
112
+ railties (6.0.3.4)
113
+ actionpack (= 6.0.3.4)
114
+ activesupport (= 6.0.3.4)
115
+ method_source
116
+ rake (>= 0.8.7)
117
+ thor (>= 0.20.3, < 2.0)
118
+ rake (13.0.1)
119
+ sprockets (4.0.2)
120
+ concurrent-ruby (~> 1.0)
121
+ rack (> 1, < 3)
122
+ sprockets-rails (3.2.2)
123
+ actionpack (>= 4.0)
124
+ activesupport (>= 4.0)
125
+ sprockets (>= 3.0.0)
126
+ thor (1.0.1)
127
+ thread_safe (0.3.6)
128
+ tzinfo (1.2.7)
129
+ thread_safe (~> 0.1)
130
+ websocket-driver (0.7.3)
131
+ websocket-extensions (>= 0.1.0)
132
+ websocket-extensions (0.1.5)
133
+ zeitwerk (2.4.0)
134
+
135
+ PLATFORMS
136
+ ruby
137
+
138
+ DEPENDENCIES
139
+ active_record-union_relation!
140
+ minitest (~> 5.14)
141
+ pg (~> 1.2)
142
+ rails (~> 6.0)
143
+ rake (~> 13.0)
144
+
145
+ BUNDLED WITH
146
+ 2.1.4
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020-present Kevin Deisz
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.
@@ -0,0 +1,109 @@
1
+ # ActiveRecord::UnionRelation
2
+
3
+ [![Build Status](https://github.com/kddeisz/active_record-union_relation/workflows/Main/badge.svg)](https://github.com/kddeisz/active_record-union_relation/actions)
4
+
5
+ There are times when you want to use SQL's [UNION](https://www.w3schools.com/sql/sql_union.asp) operator to pull rows from multiple relations, but you still want to maintain the query-builder interface of ActiveRecord. This gem allows you to do that with minimal syntax.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'active_record-union_relation'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install active_record-union_relation
22
+
23
+ ## Usage
24
+
25
+ Let's assume you're writing something like a search function, and you want to be able to return a polymorphic relation containing all of the search results. You could maintain a separate index table with links out to the entities or use a more advanced search engine. Or you could perform a `UNION` that searches each table.
26
+
27
+ `UNION` subrelations must all have the same number of columns, so first we define the name of the columns that the `UNION` will select, then we define the sources that will become those columns from each subrelation. It makes most sense looking at an example.
28
+
29
+ Let's assume we have the following structure with default table names:
30
+
31
+ ```ruby
32
+ class Comment < ActiveRecord::Base
33
+ belongs_to :post
34
+ end
35
+
36
+ class Post < ActiveRecord::Base
37
+ has_many :comments
38
+ end
39
+
40
+ class Tag < ActiveRecord::Base
41
+ end
42
+ ```
43
+
44
+ Now, let's pull all of the records matching a specific term. For `Post`, we'll pull `published: true` records that have a `title` matching the term. For `Comment`, we'll pull the records that have a `body` matching the term. And finally, for `Tag`, we'll pull records that have a `name` matching the term.
45
+
46
+ ```ruby
47
+ # Let's get a local variable that we'll use to reference within each of our
48
+ # subqueries. Presumably this would come from some kind of user input.
49
+ term = 'foo'
50
+
51
+ # First, we call ActiveRecord::union. The arguments are the names of the columns
52
+ # that will be aliased from each source relation. It also accepts a block that
53
+ # is used to configure the union's subqueries.
54
+ relation =
55
+ ActiveRecord.union(:id, :post_id, :matched) do |union|
56
+ # Okay, now we're going to pull the post records into a subquery. First,
57
+ # we'll get a posts variable that contains the relation that we want to pull
58
+ # just for this one table. That can include any kind of
59
+ # joins/conditions/orders etc. that it needs to. In this case we'll need
60
+ # published: true and a matching query.
61
+ posts = Post.where(published: true).where('title LIKE ?', "%#{term}%")
62
+
63
+ # Next, we'll add that posts relation as a subquery into the union. The
64
+ # number of arguments here must directly align with the number of arguments
65
+ # given to the overall union. In this case to line everything up, we'll
66
+ # select id as the id column, nil as a placeholder since we don't need
67
+ # anything for the post_id column, and title as the matched column.
68
+ union.add posts, :id, nil, :title
69
+
70
+ # Next we'll pull the comments relation that we want into its own variable,
71
+ # and then add it into the overall union. We'll line up the id column to id,
72
+ # the post_id column to post_id, and the body to matched. Since we're
73
+ # explicitly pulling post_id, we'll actually be able to call .post on the
74
+ # comment records that get pulled since we alias them back when we
75
+ # instantiate the objects.
76
+ comments = Comment.where('body LIKE ?', "%#{term}%")
77
+ union.add comments, :id, :post_id, :body
78
+
79
+ # Finally, we'll pull the tag records that we want and add them into the
80
+ # overall union as well.
81
+ tags = Tag.where('name LIKE ?', "%#{term}%")
82
+ union.add tags, :id, nil, :name
83
+ end
84
+
85
+ # Now we have a relation object that represents the UNION, and we can perform
86
+ # all of the mutations that we would normally perform on a relation.
87
+ relation.order(matched: :asc)
88
+
89
+ # This results in a polymorphic response that once we load the records has
90
+ # everything loaded and aliased properly, as in:
91
+ #
92
+ # [#<Tag:0x00 id: 3, name: "foo">,
93
+ # #<Post:0x000 id: 2, title: "foo published">,
94
+ # #<Comment:0x00 id: 3, post_id: 2, body: "This is a comment with foo in it">]
95
+ ```
96
+
97
+ ## Development
98
+
99
+ 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.
100
+
101
+ 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).
102
+
103
+ ## Contributing
104
+
105
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kddeisz/active_record-union_relation.
106
+
107
+ ## License
108
+
109
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/*_test.rb']
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/active_record/union_relation/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'active_record-union_relation'
7
+ spec.version = ActiveRecord::UnionRelation::VERSION
8
+ spec.authors = ['Kevin Deisz']
9
+ spec.email = ['kevin.deisz@gmail.com']
10
+
11
+ spec.summary = 'Create ActiveRecord relations from UNIONs'
12
+ spec.homepage = 'https://github.com/kddeisz/active_record-union_relation'
13
+ spec.license = 'MIT'
14
+
15
+ spec.files = Dir.chdir(__dir__) do
16
+ `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ end
20
+
21
+ spec.bindir = 'exe'
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ['lib']
24
+
25
+ spec.add_dependency 'activerecord', '>= 6'
26
+
27
+ spec.add_development_dependency 'minitest', '~> 5.14'
28
+ spec.add_development_dependency 'pg', '~> 1.2'
29
+ spec.add_development_dependency 'rails', '~> 6.0'
30
+ spec.add_development_dependency 'rake', '~> 13.0'
31
+ end
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'active_record/union_relation'
5
+
6
+ require 'irb'
7
+ IRB.start(__FILE__)
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record'
4
+ require 'active_record/union_relation/version'
5
+
6
+ module ActiveRecord
7
+ class UnionRelation
8
+ class Error < StandardError
9
+ end
10
+
11
+ # Unions require that the number of columns coming from each subrelation all
12
+ # match. When we pull the attributes out an instantiate the actual objects,
13
+ # we then map them back to the original attribute names.
14
+ class MismatchedColumnsError < Error
15
+ def initialize(columns, sources)
16
+ super("Expected #{columns.length} columns but got #{sources.length}")
17
+ end
18
+ end
19
+
20
+ # If you attempt to use a union before you've added any subqueries, we'll
21
+ # raise this error so there's not some weird undefined method behavior.
22
+ class NoConfiguredSubqueriesError < Error
23
+ def initialize
24
+ super('No subqueries have been configured for this union')
25
+ end
26
+ end
27
+
28
+ # This represents a combination of an ActiveRecord::Relation and a set of
29
+ # columns that it will pull.
30
+ class Subquery
31
+ # Sometimes you need some columns in some subqeries that you don't need in
32
+ # others. In order to accomplish that and still maintain the matching
33
+ # number of columns, you can put a null in space of a column instead.
34
+ NULL = Arel.sql('NULL')
35
+
36
+ attr_reader :relation, :model_name, :sources
37
+
38
+ def initialize(relation, sources)
39
+ @relation = relation
40
+ @model_name = relation.model.name
41
+ @sources = sources.map { |source| source ? source.to_s : NULL }
42
+ end
43
+
44
+ def to_arel(columns, discriminator)
45
+ relation
46
+ .select(
47
+ Arel.sql("'#{model_name}'").as(quote_column_name(discriminator)),
48
+ *sources.zip(columns).map do |(source, column)|
49
+ Arel.sql(source.to_s).as(quote_column_name(column))
50
+ end
51
+ )
52
+ .arel
53
+ end
54
+
55
+ def to_mapping(columns)
56
+ [model_name, columns.zip(sources).to_h]
57
+ end
58
+
59
+ private
60
+
61
+ def quote_column_name(name)
62
+ relation.model.connection.quote_column_name(name)
63
+ end
64
+ end
65
+
66
+ attr_reader :columns, :discriminator, :subqueries
67
+
68
+ def initialize(columns, discriminator)
69
+ @columns = columns.map(&:to_s)
70
+ @discriminator = discriminator
71
+ @subqueries = []
72
+ end
73
+
74
+ # Adds a subquery to the overall union.
75
+ def add(relation, *sources)
76
+ if columns.length != sources.length
77
+ raise MismatchedColumnsError.new(columns, sources)
78
+ end
79
+
80
+ subqueries << Subquery.new(relation, sources)
81
+ end
82
+
83
+ # Creates an ActiveRecord::Relation object that will pull all of the
84
+ # subqueries together.
85
+ def all
86
+ raise NoConfiguredSubqueriesError if subqueries.empty?
87
+
88
+ model = subqueries.first.relation.model
89
+ subclass_for(model).from(union_for(model)).select(discriminator, *columns)
90
+ end
91
+
92
+ private
93
+
94
+ def subclass_for(model)
95
+ discriminator = self.discriminator
96
+ mappings = subqueries.to_h { |subquery| subquery.to_mapping(columns) }
97
+
98
+ Class.new(model) do
99
+ define_singleton_method(:inheritance_column) { discriminator }
100
+ define_singleton_method(:instantiate) do |attributes, column_types = {}, &block|
101
+ type = attributes.delete(inheritance_column)
102
+
103
+ instantiate_instance_of(
104
+ Object.const_get(type),
105
+ attributes.transform_keys(&mappings[type]),
106
+ column_types,
107
+ &block
108
+ )
109
+ end
110
+ end
111
+ end
112
+
113
+ def union_for(model)
114
+ Arel::Nodes::As.new(
115
+ subqueries
116
+ .map { |subquery| subquery.to_arel(columns, discriminator) }
117
+ .inject { |left, right| Arel::Nodes::Union.new(left, right) },
118
+ Arel.sql(model.connection.quote_table_name('union'))
119
+ )
120
+ end
121
+ end
122
+
123
+ # Unions require that you have an equal number of columns from each
124
+ # subquery. The columns argument being passed here is any number of
125
+ # symbols that represent the columns that will be queried. When you then go
126
+ # to add sources into the union you'll need to pass the same number of
127
+ # columns.
128
+ #
129
+ # One additional column will be added to the query in order to discriminate
130
+ # between all of the unioned types. Then when the objects are going to be
131
+ # instantiated, we map the columns back to their original names.
132
+ def self.union(*columns, discriminator: 'discriminator')
133
+ UnionRelation.new(columns, discriminator).tap { |union| yield union }.all
134
+ end
135
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ class UnionRelation
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
metadata ADDED
@@ -0,0 +1,129 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_record-union_relation
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Kevin Deisz
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-10-08 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: '6'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6'
27
+ - !ruby/object:Gem::Dependency
28
+ name: minitest
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '5.14'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '5.14'
41
+ - !ruby/object:Gem::Dependency
42
+ name: pg
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.2'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.2'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rails
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '6.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '6.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '13.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '13.0'
83
+ description:
84
+ email:
85
+ - kevin.deisz@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".github/dependabot.yml"
91
+ - ".github/workflows/main.yml"
92
+ - ".gitignore"
93
+ - ".mergify.yml"
94
+ - CHANGELOG.md
95
+ - CODE_OF_CONDUCT.md
96
+ - Gemfile
97
+ - Gemfile.lock
98
+ - LICENSE
99
+ - README.md
100
+ - Rakefile
101
+ - active_record-union_relation.gemspec
102
+ - bin/console
103
+ - bin/setup
104
+ - lib/active_record/union_relation.rb
105
+ - lib/active_record/union_relation/version.rb
106
+ homepage: https://github.com/kddeisz/active_record-union_relation
107
+ licenses:
108
+ - MIT
109
+ metadata: {}
110
+ post_install_message:
111
+ rdoc_options: []
112
+ require_paths:
113
+ - lib
114
+ required_ruby_version: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - ">="
117
+ - !ruby/object:Gem::Version
118
+ version: '0'
119
+ required_rubygems_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ requirements: []
125
+ rubygems_version: 3.1.2
126
+ signing_key:
127
+ specification_version: 4
128
+ summary: Create ActiveRecord relations from UNIONs
129
+ test_files: []