dbee-active_record 1.0.0.pre.alpha

Sign up to get free protection for your applications and to get access to all the features.
Files changed (39) hide show
  1. checksums.yaml +7 -0
  2. data/.editorconfig +8 -0
  3. data/.gitignore +7 -0
  4. data/.rubocop.yml +27 -0
  5. data/.ruby-version +1 -0
  6. data/.travis.yml +30 -0
  7. data/CHANGELOG.md +7 -0
  8. data/CODE_OF_CONDUCT.md +74 -0
  9. data/Gemfile +5 -0
  10. data/Guardfile +16 -0
  11. data/LICENSE +7 -0
  12. data/README.md +75 -0
  13. data/Rakefile +15 -0
  14. data/bin/console +18 -0
  15. data/dbee-active_record.gemspec +36 -0
  16. data/lib/dbee/providers/active_record_provider/expression_builder/constraint_maker.rb +50 -0
  17. data/lib/dbee/providers/active_record_provider/expression_builder/order_maker.rb +23 -0
  18. data/lib/dbee/providers/active_record_provider/expression_builder/select_maker.rb +31 -0
  19. data/lib/dbee/providers/active_record_provider/expression_builder/where_maker.rb +54 -0
  20. data/lib/dbee/providers/active_record_provider/expression_builder.rb +169 -0
  21. data/lib/dbee/providers/active_record_provider/obfuscated_alias_maker.rb +40 -0
  22. data/lib/dbee/providers/active_record_provider/safe_alias_maker.rb +21 -0
  23. data/lib/dbee/providers/active_record_provider/version.rb +16 -0
  24. data/lib/dbee/providers/active_record_provider.rb +51 -0
  25. data/spec/config/database.yaml.ci +9 -0
  26. data/spec/db_helper.rb +56 -0
  27. data/spec/dbee/providers/active_record_provider_spec.rb +79 -0
  28. data/spec/fixtures/active_record_snapshots/five_table_query.yaml +77 -0
  29. data/spec/fixtures/active_record_snapshots/multiple_same_table_query_with_static_constraints.yaml +104 -0
  30. data/spec/fixtures/active_record_snapshots/one_table_query.yaml +26 -0
  31. data/spec/fixtures/active_record_snapshots/one_table_query_with_ascending_sort.yaml +31 -0
  32. data/spec/fixtures/active_record_snapshots/one_table_query_with_descending_sort.yaml +32 -0
  33. data/spec/fixtures/active_record_snapshots/one_table_query_with_filters.yaml +170 -0
  34. data/spec/fixtures/active_record_snapshots/one_table_query_with_limit.yaml +30 -0
  35. data/spec/fixtures/active_record_snapshots/one_table_query_with_multiple_sorts.yaml +33 -0
  36. data/spec/fixtures/active_record_snapshots/two_table_query.yaml +44 -0
  37. data/spec/fixtures/models.yaml +66 -0
  38. data/spec/spec_helper.rb +52 -0
  39. metadata +256 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9a9c401d5b1bb61ca60f0ee1c1fd6c6f76d68fc768b7e35d0d885e5d66c1bcb9
4
+ data.tar.gz: 102ab3f38c5074992cde4a8e0a059a09fff22face4dc392bf7633fbbb1a00aad
5
+ SHA512:
6
+ metadata.gz: fd65b523a86d65171ee3f603ac92a773ff5a29d6bc73706168048d01b1db7a28892c6534feb7e9603a8d1b6e7ba58e8c6bf801f0d870d5e0d616d009c330684b
7
+ data.tar.gz: c916e056d09e1564a43a1f4306b2671cff7b62f94efbf40ca2fcf32443bc6aceed083cc249fdbf778c6dbef423c28039a3cab98974e71828fb704442720a9f57
data/.editorconfig ADDED
@@ -0,0 +1,8 @@
1
+ # See http://editorconfig.org/
2
+
3
+ [*]
4
+ trim_trailing_whitespace = true
5
+ indent_style = space
6
+ indent_size = 2
7
+ insert_final_newline = true
8
+ end_of_line = lf
data/.gitignore ADDED
@@ -0,0 +1,7 @@
1
+ .DS_Store
2
+ *.gem
3
+ /tmp
4
+ /coverage
5
+ Gemfile.lock
6
+ /pkg
7
+ /spec/config/database.yaml
data/.rubocop.yml ADDED
@@ -0,0 +1,27 @@
1
+ Metrics/LineLength:
2
+ Max: 100
3
+
4
+ Metrics/BlockLength:
5
+ ExcludedMethods:
6
+ - let
7
+ - it
8
+ - describe
9
+ - context
10
+ - specify
11
+ - define
12
+
13
+ Metrics/MethodLength:
14
+ Max: 25
15
+ Exclude:
16
+ - spec/db_helper.rb
17
+
18
+ AllCops:
19
+ TargetRubyVersion: 2.3
20
+
21
+ Metrics/AbcSize:
22
+ Max: 16
23
+ Exclude:
24
+ - spec/db_helper.rb
25
+
26
+ Metrics/ClassLength:
27
+ Max: 125
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.6.3
data/.travis.yml ADDED
@@ -0,0 +1,30 @@
1
+ env:
2
+ global:
3
+ - CC_TEST_REPORTER_ID=036a8fd92cf0c323c9704c041015837d14889e47de936bab18287626ff3372c1
4
+ language: ruby
5
+ services:
6
+ - mysql
7
+ rvm:
8
+ # Build on the latest stable of all supported Rubies (https://www.ruby-lang.org/en/downloads/):
9
+ - 2.3.8
10
+ - 2.4.5
11
+ - 2.5.3
12
+ - 2.6.0
13
+ - 2.6.3
14
+ cache: bundler
15
+ before_script:
16
+ - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
17
+ - chmod +x ./cc-test-reporter
18
+ - ./cc-test-reporter before-build
19
+ - cp spec/config/database.yaml.ci spec/config/database.yaml
20
+ - mysql -e 'CREATE DATABASE IF NOT EXISTS dbee_test;'
21
+ script:
22
+ - bundle exec rubocop
23
+ - bundle exec rspec spec --format documentation
24
+ after_script:
25
+ - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
26
+ addons:
27
+ # https://docs.travis-ci.com/user/uploading-artifacts/
28
+ artifacts:
29
+ paths:
30
+ - Gemfile.lock
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # 1.0.0-alpha (August 20th, 2019)
2
+
3
+ Added initial implementation.
4
+
5
+ # 0.0.1 (August 18th, 2019)
6
+
7
+ Initial library shell published.
@@ -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 oss@bluemarblepayroll.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 [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://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
data/Guardfile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ guard :rspec, cmd: 'DISABLE_SIMPLECOV=true bundle exec rspec --format=documentation' do
4
+ require 'guard/rspec/dsl'
5
+ dsl = Guard::RSpec::Dsl.new(self)
6
+
7
+ # RSpec files
8
+ rspec = dsl.rspec
9
+ watch(rspec.spec_helper) { rspec.spec_dir }
10
+ watch(rspec.spec_support) { rspec.spec_dir }
11
+ watch(rspec.spec_files)
12
+
13
+ # Ruby files
14
+ ruby = dsl.ruby
15
+ dsl.watch_spec_files_for(ruby.lib_files)
16
+ end
data/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2019 Blue Marble Payroll, LLC
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # Dbee Active Record Provider
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/dbee-active_record.svg)](https://badge.fury.io/rb/dbee-active_record) [![Build Status](https://travis-ci.org/bluemarblepayroll/dbee-active_record.svg?branch=master)](https://travis-ci.org/bluemarblepayroll/dbee-active_record) [![Maintainability](https://api.codeclimate.com/v1/badges/7f74a4e546bebb603cce/maintainability)](https://codeclimate.com/github/bluemarblepayroll/dbee-active_record/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/7f74a4e546bebb603cce/test_coverage)](https://codeclimate.com/github/bluemarblepayroll/dbee-active_record/test_coverage) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ Dbee does not ship with a SQL generator by default. This library plugs into Dbee to provide SQL generation via ActiveRecord. Technically speaking: this library does not use ActiveRecord for anything except connection information. All actual SQL generation is performed using Arel. There is no actual coupling of your domain ActiveRecord subclasses to Dbee.
6
+
7
+ This library is a plugin for [Dbee](https://github.com/bluemarblepayroll/dbee). The Dbee repositories README file contains information about how to use the Data Model and Query API's.
8
+
9
+ ## Installation
10
+
11
+ To install through Rubygems:
12
+
13
+ ````
14
+ gem install install dbee-active_record
15
+ ````
16
+
17
+ You can also add this to your Gemfile:
18
+
19
+ ````
20
+ bundle add dbee-active_record
21
+ ````
22
+
23
+ ## Contributing
24
+
25
+ ### Development Environment Configuration
26
+
27
+ Basic steps to take to get this repository compiling:
28
+
29
+ 1. Install [Ruby](https://www.ruby-lang.org/en/documentation/installation/) (check dbee-active_record.gemspec for versions supported)
30
+ 2. Install bundler (gem install bundler)
31
+ 3. Clone the repository (git clone git@github.com:bluemarblepayroll/dbee-active_record.git)
32
+ 4. Navigate to the root folder (cd dbee-active_record)
33
+ 5. Install dependencies (bundle)
34
+ 6. Copy spec/config/database.yaml.ci to spec/config/database.yaml. Customize both sqlite and mysql connections per your local environment.
35
+
36
+ ### Running Tests
37
+
38
+ To execute the test suite run:
39
+
40
+ ````bash
41
+ bundle exec rspec spec --format documentation
42
+ ````
43
+
44
+ Alternatively, you can have Guard watch for changes:
45
+
46
+ ````bash
47
+ bundle exec guard
48
+ ````
49
+
50
+ Also, do not forget to run Rubocop:
51
+
52
+ ````bash
53
+ bundle exec rubocop
54
+ ````
55
+
56
+ ### Publishing
57
+
58
+ Note: ensure you have proper authorization before trying to publish new versions.
59
+
60
+ After code changes have successfully gone through the Pull Request review process then the following steps should be followed for publishing new versions:
61
+
62
+ 1. Merge Pull Request into master
63
+ 2. Update `lib/dbee-active_record/version.rb` using [semantic versioning](https://semver.org/)
64
+ 3. Install dependencies: `bundle`
65
+ 4. Update `CHANGELOG.md` with release notes
66
+ 5. Commit & push master to remote and ensure CI builds master successfully
67
+ 6. 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).
68
+
69
+ ## Code of Conduct
70
+
71
+ Everyone interacting in this codebase, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/bluemarblepayroll/dbee-active_record/blob/master/CODE_OF_CONDUCT.md).
72
+
73
+ ## License
74
+
75
+ This project is MIT Licensed.
data/Rakefile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright (c) 2019-present, Blue Marble Payroll, LLC
5
+ #
6
+ # This source code is licensed under the MIT license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+ #
9
+
10
+ require 'bundler/gem_tasks'
11
+ require 'rspec/core/rake_task'
12
+
13
+ RSpec::Core::RakeTask.new(:spec)
14
+
15
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # Copyright (c) 2018-present, Blue Marble Payroll, LLC
6
+ #
7
+ # This source code is licensed under the MIT license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+ #
10
+
11
+ require 'bundler/setup'
12
+ require 'dbee/providers/active_record_provider'
13
+
14
+ # You can add fixtures and/or initialization code here to make experimenting
15
+ # with your gem easier. You can also use a different console, if you like.
16
+
17
+ require 'pry'
18
+ Pry.start
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require './lib/dbee/providers/active_record_provider/version'
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = 'dbee-active_record'
7
+ s.version = Dbee::Providers::ActiveRecordProvider::VERSION
8
+ s.summary = 'Plugs in ActiveRecord so Dbee can use Arel for SQL generation.'
9
+
10
+ s.description = <<-DESCRIPTION
11
+ By default Dbee ships with no underlying SQL generator. This library will plug in ActiveRecord into Dbee and Dbee will use it for SQL generation.
12
+ DESCRIPTION
13
+
14
+ s.authors = ['Matthew Ruggio']
15
+ s.email = ['mruggio@bluemarblepayroll.com']
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
19
+ s.homepage = 'https://github.com/bluemarblepayroll/dbee-active_record'
20
+ s.license = 'MIT'
21
+
22
+ s.required_ruby_version = '>= 2.3.8'
23
+
24
+ s.add_dependency('activerecord', '~>5', '>=5.2.1')
25
+ s.add_dependency('dbee', '>=1.0.0.pre.alpha.1')
26
+
27
+ s.add_development_dependency('guard-rspec', '~>4.7')
28
+ s.add_development_dependency('mysql2', '~>0.5')
29
+ s.add_development_dependency('pry', '~>0')
30
+ s.add_development_dependency('rake', '~> 12')
31
+ s.add_development_dependency('rspec', '~> 3.8')
32
+ s.add_development_dependency('rubocop', '~>0.63.1')
33
+ s.add_development_dependency('simplecov', '~>0.16.1')
34
+ s.add_development_dependency('simplecov-console', '~>0.4.2')
35
+ s.add_development_dependency('sqlite3', '~>1')
36
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright (c) 2019-present, Blue Marble Payroll, LLC
5
+ #
6
+ # This source code is licensed under the MIT license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+ #
9
+
10
+ module Dbee
11
+ module Providers
12
+ class ActiveRecordProvider
13
+ class ExpressionBuilder
14
+ # Can derive constraints for Arel table JOIN statements.
15
+ class ConstraintMaker
16
+ CONCAT_METHOD = lambda do |on, arel_column, value|
17
+ on ? on.and(arel_column.eq(value)) : arel_column.eq(value)
18
+ end
19
+
20
+ METHODS = {
21
+ Model::Constraints::Reference => lambda do |constraint, on, table, previous_table|
22
+ name = constraint.name
23
+ parent = constraint.parent
24
+
25
+ CONCAT_METHOD.call(on, table[name], previous_table[parent])
26
+ end,
27
+ Model::Constraints::Static => lambda do |constraint, on, table, _previous_table|
28
+ name = constraint.name
29
+ value = constraint.value
30
+
31
+ CONCAT_METHOD.call(on, table[name], value)
32
+ end
33
+ }.freeze
34
+
35
+ private_constant :METHODS
36
+
37
+ def make(constraints, table, previous_table)
38
+ constraints.inject(nil) do |memo, constraint|
39
+ method = METHODS[constraint.class]
40
+
41
+ raise ArgumentError, "constraint unhandled: #{constraint.class.name}" unless method
42
+
43
+ method.call(constraint, memo, table, previous_table)
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright (c) 2019-present, Blue Marble Payroll, LLC
5
+ #
6
+ # This source code is licensed under the MIT license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+ #
9
+
10
+ module Dbee
11
+ module Providers
12
+ class ActiveRecordProvider
13
+ class ExpressionBuilder
14
+ # Derives Arel#order predicates.
15
+ class OrderMaker
16
+ def make(sorter, arel_column)
17
+ sorter.ascending? ? arel_column : arel_column.desc
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright (c) 2019-present, Blue Marble Payroll, LLC
5
+ #
6
+ # This source code is licensed under the MIT license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+ #
9
+
10
+ module Dbee
11
+ module Providers
12
+ class ActiveRecordProvider
13
+ class ExpressionBuilder
14
+ # Derives Arel#project predicates.
15
+ class SelectMaker
16
+ def make(column, arel_column, alias_maker)
17
+ column_alias = quote(alias_maker.make(column.display))
18
+
19
+ arel_column.as(column_alias)
20
+ end
21
+
22
+ private
23
+
24
+ def quote(value)
25
+ ActiveRecord::Base.connection.quote(value)
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright (c) 2019-present, Blue Marble Payroll, LLC
5
+ #
6
+ # This source code is licensed under the MIT license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+ #
9
+
10
+ module Dbee
11
+ module Providers
12
+ class ActiveRecordProvider
13
+ class ExpressionBuilder
14
+ # Derives Arel#where predicates.
15
+ class WhereMaker
16
+ METHODS = {
17
+ Query::Filters::Contains => ->(column, val) { column.matches("%#{val}%") },
18
+ Query::Filters::Equals => ->(column, val) { column.eq(val) },
19
+ Query::Filters::GreaterThan => ->(column, val) { column.gt(val) },
20
+ Query::Filters::GreaterThanOrEqualTo => ->(column, val) { column.gteq(val) },
21
+ Query::Filters::LessThan => ->(column, val) { column.lt(val) },
22
+ Query::Filters::LessThanOrEqualTo => ->(column, val) { column.lteq(val) },
23
+ Query::Filters::NotContain => ->(column, val) { column.does_not_match("%#{val}%") },
24
+ Query::Filters::NotEquals => ->(column, val) { column.not_eq(val) },
25
+ Query::Filters::NotStartWith => ->(column, val) { column.does_not_match("#{val}%") },
26
+ Query::Filters::StartsWith => ->(column, val) { column.matches("#{val}%") }
27
+ }.freeze
28
+
29
+ private_constant :METHODS
30
+
31
+ def make(filter, arel_column, model_column)
32
+ coerced_values = Array(filter.value).map { |v| model_column.coerce(v) }
33
+
34
+ predicates = coerced_values.map do |coerced_value|
35
+ method = METHODS[filter.class]
36
+
37
+ raise ArgumentError, "cannot compile filter: #{filter}" unless method
38
+
39
+ method.call(arel_column, coerced_value)
40
+ end
41
+
42
+ clause = predicates.shift
43
+
44
+ predicates.each do |predicate|
45
+ clause = clause.or(predicate)
46
+ end
47
+
48
+ clause
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright (c) 2019-present, Blue Marble Payroll, LLC
5
+ #
6
+ # This source code is licensed under the MIT license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+ #
9
+
10
+ require_relative 'expression_builder/constraint_maker'
11
+ require_relative 'expression_builder/order_maker'
12
+ require_relative 'expression_builder/select_maker'
13
+ require_relative 'expression_builder/where_maker'
14
+
15
+ module Dbee
16
+ module Providers
17
+ class ActiveRecordProvider
18
+ # This class can generate an Arel expression tree.
19
+ class ExpressionBuilder
20
+ extend Forwardable
21
+
22
+ def_delegators :statement, :to_sql
23
+
24
+ def initialize(model, table_alias_maker, column_alias_maker)
25
+ @model = model
26
+ @table_alias_maker = table_alias_maker
27
+ @column_alias_maker = column_alias_maker
28
+
29
+ @base_table = Arel::Table.new(model.table)
30
+ @base_table.table_alias = table_alias_maker.make(model.name)
31
+
32
+ @statement = base_table
33
+ end
34
+
35
+ def add(query)
36
+ query.fields.each { |field| add_field(field) }
37
+ query.sorters.each { |sorter| add_sorter(sorter) }
38
+ query.filters.each { |filter| add_filter(filter) }
39
+
40
+ add_limit(query.limit)
41
+
42
+ self
43
+ end
44
+
45
+ private
46
+
47
+ attr_reader :base_table,
48
+ :statement,
49
+ :model,
50
+ :table_alias_maker,
51
+ :column_alias_maker
52
+
53
+ def tables
54
+ @tables ||= {}
55
+ end
56
+
57
+ def key_paths_to_arel_columns
58
+ @key_paths_to_arel_columns ||= {}
59
+ end
60
+
61
+ def key_paths_to_model_columns
62
+ @key_paths_to_model_columns ||= {}
63
+ end
64
+
65
+ def where_maker
66
+ @where_maker ||= WhereMaker.new
67
+ end
68
+
69
+ def order_maker
70
+ @order_maker ||= OrderMaker.new
71
+ end
72
+
73
+ def select_maker
74
+ @select_maker ||= SelectMaker.new
75
+ end
76
+
77
+ def constraint_maker
78
+ @constraint_maker ||= ConstraintMaker.new
79
+ end
80
+
81
+ def add_filter(filter)
82
+ add_key_path(filter.key_path)
83
+
84
+ key_path = filter.key_path
85
+ arel_column = key_paths_to_arel_columns[key_path]
86
+ model_column = key_paths_to_model_columns[key_path]
87
+
88
+ predicate = where_maker.make(filter, arel_column, model_column)
89
+
90
+ @statement = statement.where(predicate)
91
+
92
+ self
93
+ end
94
+
95
+ def add_sorter(sorter)
96
+ add_key_path(sorter.key_path)
97
+
98
+ key_path = sorter.key_path
99
+ arel_column = key_paths_to_arel_columns[key_path]
100
+
101
+ predicate = order_maker.make(sorter, arel_column)
102
+
103
+ @statement = statement.order(predicate)
104
+
105
+ self
106
+ end
107
+
108
+ def add_field(field)
109
+ add_key_path(field.key_path)
110
+
111
+ key_path = field.key_path
112
+ arel_column = key_paths_to_arel_columns[key_path]
113
+
114
+ predicate = select_maker.make(field, arel_column, column_alias_maker)
115
+
116
+ @statement = statement.project(predicate)
117
+
118
+ self
119
+ end
120
+
121
+ def add_limit(limit)
122
+ @limit = limit ? limit.to_i : nil
123
+
124
+ @statement = @statement.take(limit) if limit
125
+
126
+ self
127
+ end
128
+
129
+ def model_column(ancestors, key_path)
130
+ model_column = (ancestors.values.last || model).column(key_path.column_name)
131
+ key_paths_to_model_columns[key_path] = model_column
132
+ end
133
+
134
+ def table(name, model, previous_table)
135
+ table = Arel::Table.new(model.table)
136
+ table.table_alias = table_alias_maker.make(name)
137
+
138
+ on = constraint_maker.make(model.constraints, table, previous_table)
139
+
140
+ @statement = statement.join(table, ::Arel::Nodes::OuterJoin)
141
+ @statement = statement.on(on) if on
142
+
143
+ tables[name] = table
144
+ end
145
+
146
+ def traverse_ancestors(ancestors)
147
+ ancestors.each_pair.inject(base_table) do |memo, (name, model)|
148
+ tables.key?(name) ? tables[name] : table(name, model, memo)
149
+ end
150
+ end
151
+
152
+ def add_key_path(key_path)
153
+ return if key_paths_to_arel_columns.key?(key_path)
154
+
155
+ ancestors = model.ancestors(key_path.ancestor_names)
156
+
157
+ model_column(ancestors, key_path)
158
+
159
+ table = traverse_ancestors(ancestors)
160
+
161
+ arel_column = table[key_path.column_name]
162
+ key_paths_to_arel_columns[key_path] = arel_column
163
+
164
+ self
165
+ end
166
+ end
167
+ end
168
+ end
169
+ end