esql 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3d0ec66abeb7fa4a711ecc8c7a73be80099c12f3b3211f4814e8e756ab3e1316
4
+ data.tar.gz: d417589cec6723ff1f8e383a4e00c472766634a654f0f537cee66b75fad39f97
5
+ SHA512:
6
+ metadata.gz: ba188083f0290e75860dc3ba2dcfa2bcd1176b7826f570bf8dbba308b75aabedb9490bc730904b6d79e943d03600780bc7e12162e548c2307d2a4df0297d8f73
7
+ data.tar.gz: 2e039c4b8baa125b3a6412a3a780cee6eb9bebb26a4e44239889f5541c554aa6a85ee4f0254f5864612f927e8b039d16b74ffd24509bb3a6f64a0fc0ce119936
@@ -0,0 +1,15 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ **/.DS_Store
14
+
15
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.0
6
+ before_install: gem install bundler -v 2.1.4
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Paul Holden
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,113 @@
1
+ # esql
2
+
3
+ Esql is a library for ActiveRecord scoping using simple expressions.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```rb
10
+ gem 'esql'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install esql
20
+
21
+ ## Usage
22
+
23
+ This gem is easy to use: all you need is an ActiveRecord scope and an
24
+ expression. The result is a scope with any necessary joins applied, to which
25
+ you can use to generate columns, sort results, or apply filters.
26
+
27
+ One of the primary goals is to allow your applications to unlock the full
28
+ power of SQL without having to hard-code queries or fret about SQL injection.
29
+
30
+ ```rb
31
+ ast = Esql::Parser.new.parse('concat(first_name, " ", last_name)')
32
+ scope, sql = ast.evaluate(Employee.all)
33
+ ```
34
+
35
+ Esql is a minimalist gem. A common use case is generating columns using
36
+ formulas or aggregates. By default they won't be `SELECT`ed (because you
37
+ might want to use your expressions to filter results instead); you will need
38
+ to do that yourself. You can monkey patch the following method to allow
39
+ adding a new column to your `SELECT` list instead of having to write the
40
+ entire list again:
41
+
42
+ ```rb
43
+ # Put this in an initializer
44
+ module ActiveRecord
45
+ class Relation
46
+ def select_append(*fields)
47
+ fields.unshift(arel_table[Arel.star]) if !select_values.any?
48
+ select(*fields)
49
+ end
50
+ end
51
+ end
52
+ ```
53
+
54
+ Another great example of how you can use Esql is as a way to support
55
+ dynamic queries in your REST APIs:
56
+
57
+ ```rb
58
+ class EmployeesController < ApplicationRecord
59
+ # GET /employees?filter[]=...
60
+ def index
61
+ scope = Employee.all
62
+ filters = request.params.fetch('filter', [])
63
+ filters.each { |expr|
64
+ ast = Esql::Parser.new.parse(expr)
65
+ scope, sql = ast.evaluate(scope)
66
+ scope = scope.where(sql)
67
+ }
68
+ render # ...
69
+ end
70
+ end
71
+ ```
72
+
73
+ Yes, you will receive a raw SQL string when your expression is evaluated.
74
+ Esql is basically a SQL transpiler—a memoizing parsing expression grammar is
75
+ used behind the scenes to ensure e.g. string literals are always properly
76
+ quoted before being inserted into the resulting SQL.
77
+
78
+ ## Expressions
79
+
80
+ The expression syntax is simple and unopinionated. As a transpiler, Esql
81
+ basically defers to SQL's rules. It just provides syntactic sugar for things
82
+ like joins and aggregates.
83
+
84
+ In most cases, Esql can catch issues like improper use of a related
85
+ attributes (i.e. attributes of related records). It does this by evaluating
86
+ the ActiveRecord reflections, so you will need to make sure you properly
87
+ define your relationships in your model classes.
88
+
89
+ Errors that get past this simple check layer (like type mismatches or even
90
+ query runtime errors) will bubble up as ActiveRecord exceptions that you'll
91
+ have to handle yourself.
92
+
93
+ ## Development
94
+
95
+ After checking out the repo, run `bin/setup` to install dependencies. Then,
96
+ run `rake spec` to run the tests. You can also run `bin/console` for an
97
+ interactive prompt that will allow you to experiment.
98
+
99
+ To install this gem onto your local machine, run `bundle exec rake install`.
100
+ To release a new version, update the version number in `version.rb`, and then
101
+ run `bundle exec rake release`, which will create a git tag for the version,
102
+ push git commits and tags, and push the `.gem` file to
103
+ [rubygems.org](https://rubygems.org).
104
+
105
+ ## Contributing
106
+
107
+ Bug reports and pull requests are welcome on GitHub at
108
+ https://github.com/paulholden2/esql.
109
+
110
+ ## License
111
+
112
+ The gem is available as open source under the terms of the
113
+ [MIT License](https://opensource.org/licenses/MIT).
@@ -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,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'esql'
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(__FILE__)
@@ -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,37 @@
1
+ require_relative 'lib/esql/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = 'esql'
5
+ spec.version = Esql::VERSION
6
+ spec.authors = ['Paul Holden']
7
+ spec.email = ['paul@codelunker.com']
8
+
9
+ spec.summary = 'A library for ActiveRecord scoping using simple expressions.'
10
+ spec.description = 'A library for ActiveRecord scoping using simple expressions.'
11
+ spec.homepage = 'https://github.com/paulholden2/esql'
12
+ spec.license = 'MIT'
13
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
14
+
15
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = 'https://github.com/paulholden2/esql'
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ end
25
+ spec.bindir = 'exe'
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ['lib']
28
+
29
+ spec.add_dependency 'activerecord'
30
+ spec.add_dependency 'babel_bridge', '~> 0.5'
31
+
32
+ spec.add_development_dependency 'rake', '~> 12.0'
33
+ spec.add_development_dependency 'rspec', '~> 3.0'
34
+ spec.add_development_dependency 'sqlite3'
35
+ spec.add_development_dependency 'factory_bot'
36
+ spec.add_development_dependency 'simplecov'
37
+ end
@@ -0,0 +1,30 @@
1
+ require 'esql/version'
2
+ require 'esql/parser'
3
+
4
+ module Esql
5
+ class Error < StandardError; end
6
+
7
+ class InvalidAttributeError < Error
8
+ def initialize(attribute)
9
+ super("No such attribute: #{attribute}")
10
+ end
11
+ end
12
+
13
+ class InvalidFunctionError < Error
14
+ def initialize(function)
15
+ super("No such function: #{function}")
16
+ end
17
+ end
18
+
19
+ class InvalidRelationshipError < Error
20
+ def initialize(relationship)
21
+ super("No such relationship: #{relationship}")
22
+ end
23
+ end
24
+
25
+ class RelationshipTypeError < Error
26
+ def initialize(relationship, actual_type)
27
+ super("#{relationship} is a #{actual_type} relationship")
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,143 @@
1
+ require 'babel_bridge'
2
+
3
+ module Esql
4
+ class Parser < BabelBridge::Parser
5
+ ignore_whitespace
6
+
7
+ def parse(expression)
8
+ super("(#{expression})")
9
+ end
10
+
11
+ rule :atom, '(', :expression, ')' do
12
+ def evaluate(scope)
13
+ scope, sql = expression.evaluate(scope)
14
+ return scope, "(#{sql})"
15
+ end
16
+ end
17
+
18
+ binary_operators_rule(
19
+ :expression,
20
+ :atom,
21
+ [
22
+ [:/, :*],
23
+ [:+, :-],
24
+ [:<, :<=, :>, :>=, :==, :!=]
25
+ ]
26
+ ) do
27
+ def evaluate(scope)
28
+ scope, lval = left.evaluate(scope)
29
+ scope, rval = right.evaluate(scope)
30
+ return scope, "#{lval} #{operator == :== ? '=' : operator} #{rval}"
31
+ end
32
+ end
33
+
34
+ rule :atom, any(
35
+ :function,
36
+ :string,
37
+ :number,
38
+ :boolean,
39
+ :related_count,
40
+ :related_attribute,
41
+ :attribute
42
+ )
43
+
44
+ rule :function, :attribute, '(', many?(:atom, ','), ')' do
45
+ def evaluate(scope)
46
+ if self.respond_to?(attribute.to_sym)
47
+ self.send(attribute.to_sym, scope, atom)
48
+ else
49
+ raise Esql::InvalidFunctionError.new(attribute)
50
+ end
51
+ end
52
+
53
+ def concat(scope, atoms)
54
+ atoms = atoms.map { |atom|
55
+ scope, sql = atom.evaluate(scope)
56
+ sql
57
+ }
58
+ return scope, "#{atoms.join(' || ')}"
59
+ end
60
+ end
61
+
62
+ rule :attribute, /[a-zA-Z_]+/ do
63
+ def evaluate(scope)
64
+ attribute = self.text
65
+ if scope.attribute_names.include?(attribute)
66
+ column_name = "#{scope.table_name}.#{attribute}"
67
+ return scope, column_name
68
+ else
69
+ raise Esql::InvalidAttributeError.new(attribute)
70
+ end
71
+ end
72
+ end
73
+
74
+ rule :related_attribute, :attribute, '.', :attribute do
75
+ def evaluate(scope)
76
+ relationship = attribute[0].text
77
+ column = attribute[1].text
78
+ reflection = scope.model.reflections[relationship]
79
+ if reflection.nil?
80
+ raise Esql::InvalidRelationshipError.new(relationship)
81
+ end
82
+ case reflection
83
+ when ActiveRecord::Reflection::BelongsToReflection,
84
+ ActiveRecord::Reflection::HasOneReflection
85
+ sql = "#{reflection.klass.table_name}.#{column}"
86
+ scope = scope.joins(relationship.to_sym)
87
+ else
88
+ t = reflection.class.to_s.demodulize.gsub(/Reflection/, '')
89
+ raise Esql::RelationshipTypeError.new(relationship, t)
90
+ end
91
+
92
+ return scope, sql
93
+ end
94
+ end
95
+
96
+ rule :related_count, :attribute, '.', /count\b/ do
97
+ def evaluate(scope)
98
+ relationship = attribute.text
99
+ reflection = scope.model.reflections[relationship]
100
+ raise Esql::InvalidRelationshipError.new(relationship) if reflection.nil?
101
+ case reflection
102
+ when ActiveRecord::Reflection::HasManyReflection
103
+ column_name = "#{relationship}__count"
104
+ foreign_key = reflection.foreign_key
105
+ primary_key = "#{scope.table_name}.#{scope.primary_key}"
106
+ scope = scope.joins(<<-SQL)
107
+ LEFT JOIN (
108
+ SELECT #{foreign_key}, COUNT(*) AS count
109
+ FROM #{reflection.klass.table_name}
110
+ GROUP BY #{foreign_key}
111
+ ) AS #{column_name}___inner
112
+ ON #{column_name}___inner.#{foreign_key} = #{primary_key}
113
+ SQL
114
+ sql = "#{column_name}___inner.count"
115
+ else
116
+ t = reflection.class.to_s.demodulize.gsub(/Reflection/, '')
117
+ raise Esql::RelationshipTypeError.new(relationship, t)
118
+ end
119
+
120
+ return scope, sql
121
+ end
122
+ end
123
+
124
+ rule :string, /"(?:[^"\\]|\\(?:["\\]))*"/ do
125
+ def evaluate(scope)
126
+ str = self.text[1...-1].gsub(/\\("|\\)/, '\1')
127
+ return scope, ActiveRecord::Base.connection.quote(str)
128
+ end
129
+ end
130
+
131
+ rule :number, /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/ do
132
+ def evaluate(scope)
133
+ return scope, self.text
134
+ end
135
+ end
136
+
137
+ rule :boolean, /(true|false)/ do
138
+ def evaluate(scope)
139
+ return scope, self.text
140
+ end
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,3 @@
1
+ module Esql
2
+ VERSION = '0.1.0'
3
+ end
metadata ADDED
@@ -0,0 +1,157 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: esql
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Paul Holden
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-09-21 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: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: babel_bridge
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.5'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.5'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '12.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '12.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: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: sqlite3
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
+ - !ruby/object:Gem::Dependency
84
+ name: factory_bot
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: simplecov
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description: A library for ActiveRecord scoping using simple expressions.
112
+ email:
113
+ - paul@codelunker.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - ".travis.yml"
121
+ - Gemfile
122
+ - LICENSE.txt
123
+ - README.md
124
+ - Rakefile
125
+ - bin/console
126
+ - bin/setup
127
+ - esql.gemspec
128
+ - lib/esql.rb
129
+ - lib/esql/parser.rb
130
+ - lib/esql/version.rb
131
+ homepage: https://github.com/paulholden2/esql
132
+ licenses:
133
+ - MIT
134
+ metadata:
135
+ allowed_push_host: https://rubygems.org
136
+ homepage_uri: https://github.com/paulholden2/esql
137
+ source_code_uri: https://github.com/paulholden2/esql
138
+ post_install_message:
139
+ rdoc_options: []
140
+ require_paths:
141
+ - lib
142
+ required_ruby_version: !ruby/object:Gem::Requirement
143
+ requirements:
144
+ - - ">="
145
+ - !ruby/object:Gem::Version
146
+ version: 2.3.0
147
+ required_rubygems_version: !ruby/object:Gem::Requirement
148
+ requirements:
149
+ - - ">="
150
+ - !ruby/object:Gem::Version
151
+ version: '0'
152
+ requirements: []
153
+ rubygems_version: 3.0.8
154
+ signing_key:
155
+ specification_version: 4
156
+ summary: A library for ActiveRecord scoping using simple expressions.
157
+ test_files: []