wise_gopher 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
+ SHA256:
3
+ metadata.gz: 7568e5308f8025d5b1f9d9cf2a869a6560b6a0377aed7ca3a79c063c5abe76ec
4
+ data.tar.gz: cd076d93f65ff85e50c4279e67604b7ba4caa6811390bdc1bbdba48197d8e50c
5
+ SHA512:
6
+ metadata.gz: 7a0d433f7e6c9dbabde1505caaa3b9a0c9318462969458d873280e0bd567c28724172fa1779f1b3163ca7334c8be2b189af9691c27654f1a26f9fc9f77e5ad57
7
+ data.tar.gz: 1517fed4b04a5c50640d8824fb9e97827905163c26155e5841dc733ef3349d3f5d27de31f8168f05bb2c9442782075cd71968edb8a42783fed61787dc6154625
@@ -0,0 +1,16 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 2.6.6
14
+ bundler-cache: true
15
+ - name: Run the default task
16
+ run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
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
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,37 @@
1
+ require:
2
+ - rubocop-rake
3
+ - rubocop-rspec
4
+
5
+ AllCops:
6
+ NewCops: enable
7
+ TargetRubyVersion: 2.5
8
+
9
+ Style/StringLiterals:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Style/StringLiteralsInInterpolation:
14
+ Enabled: true
15
+ EnforcedStyle: double_quotes
16
+
17
+ Layout/LineLength:
18
+ Max: 120
19
+ Layout/DotPosition:
20
+ EnforcedStyle: trailing
21
+ Layout/MultilineMethodCallIndentation:
22
+ EnforcedStyle: indented
23
+ Layout/HashAlignment:
24
+ EnforcedHashRocketStyle: table
25
+ EnforcedColonStyle: table
26
+
27
+ RSpec/MultipleExpectations:
28
+ Enabled: false
29
+ RSpec/NestedGroups:
30
+ Max: 4
31
+
32
+ Lint/MissingSuper:
33
+ Enabled: false
34
+
35
+ Naming/MethodParameterName:
36
+ AllowedNames:
37
+ - as
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-06-22
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at pierregabriel@me.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,101 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ wise_gopher (0.1.0)
5
+ activerecord (>= 5, < 7)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activemodel (6.1.4)
11
+ activesupport (= 6.1.4)
12
+ activerecord (6.1.4)
13
+ activemodel (= 6.1.4)
14
+ activesupport (= 6.1.4)
15
+ activesupport (6.1.4)
16
+ concurrent-ruby (~> 1.0, >= 1.0.2)
17
+ i18n (>= 1.6, < 2)
18
+ minitest (>= 5.1)
19
+ tzinfo (~> 2.0)
20
+ zeitwerk (~> 2.3)
21
+ ast (2.4.2)
22
+ byebug (11.1.3)
23
+ coderay (1.1.3)
24
+ concurrent-ruby (1.1.9)
25
+ database_cleaner (1.99.0)
26
+ diff-lcs (1.4.4)
27
+ i18n (1.8.10)
28
+ concurrent-ruby (~> 1.0)
29
+ method_source (1.0.0)
30
+ minitest (5.14.4)
31
+ parallel (1.20.1)
32
+ parser (3.0.1.1)
33
+ ast (~> 2.4.1)
34
+ pry (0.14.1)
35
+ coderay (~> 1.1)
36
+ method_source (~> 1.0)
37
+ pry-byebug (3.8.0)
38
+ byebug (~> 11.0)
39
+ pry (~> 0.10)
40
+ pry-doc (1.1.0)
41
+ pry (~> 0.11)
42
+ yard (~> 0.9.11)
43
+ rainbow (3.0.0)
44
+ rake (13.0.3)
45
+ regexp_parser (2.1.1)
46
+ rexml (3.2.5)
47
+ rspec (3.10.0)
48
+ rspec-core (~> 3.10.0)
49
+ rspec-expectations (~> 3.10.0)
50
+ rspec-mocks (~> 3.10.0)
51
+ rspec-core (3.10.1)
52
+ rspec-support (~> 3.10.0)
53
+ rspec-expectations (3.10.1)
54
+ diff-lcs (>= 1.2.0, < 2.0)
55
+ rspec-support (~> 3.10.0)
56
+ rspec-mocks (3.10.2)
57
+ diff-lcs (>= 1.2.0, < 2.0)
58
+ rspec-support (~> 3.10.0)
59
+ rspec-support (3.10.2)
60
+ rubocop (1.17.0)
61
+ parallel (~> 1.10)
62
+ parser (>= 3.0.0.0)
63
+ rainbow (>= 2.2.2, < 4.0)
64
+ regexp_parser (>= 1.8, < 3.0)
65
+ rexml
66
+ rubocop-ast (>= 1.7.0, < 2.0)
67
+ ruby-progressbar (~> 1.7)
68
+ unicode-display_width (>= 1.4.0, < 3.0)
69
+ rubocop-ast (1.7.0)
70
+ parser (>= 3.0.1.1)
71
+ rubocop-rake (0.5.1)
72
+ rubocop
73
+ rubocop-rspec (2.4.0)
74
+ rubocop (~> 1.0)
75
+ rubocop-ast (>= 1.1.0)
76
+ ruby-progressbar (1.11.0)
77
+ sqlite3 (1.4.2)
78
+ tzinfo (2.0.4)
79
+ concurrent-ruby (~> 1.0)
80
+ unicode-display_width (2.0.0)
81
+ yard (0.9.26)
82
+ zeitwerk (2.4.2)
83
+
84
+ PLATFORMS
85
+ x86_64-linux
86
+
87
+ DEPENDENCIES
88
+ database_cleaner (~> 1.5)
89
+ pry
90
+ pry-byebug
91
+ pry-doc
92
+ rake (~> 13.0)
93
+ rspec (~> 3.10)
94
+ rubocop (~> 1.7)
95
+ rubocop-rake
96
+ rubocop-rspec
97
+ sqlite3
98
+ wise_gopher!
99
+
100
+ BUNDLED WITH
101
+ 2.2.20
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Pierre Gabriel
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,232 @@
1
+ # WiseGopher
2
+
3
+ Why is the gopher wise ? Because it knows one should not use raw SQL with ActiveRecord without being mindful about security and performance !
4
+
5
+ This gem tries to solve some problems found when you need to execute custom and/or complex SQL queries for which returned data doesn't match your ActiveRecord models:
6
+
7
+ 1. ActiveRecord doesn't make it easy to use bind parameters with [`exec_query`](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-exec_query). It needs a lot of build up to pass arguments for your query.
8
+ 2. The result of query is return as an array of hashes wich deprive us of good old OOP.
9
+ 3. The column types are not always correctly retrieved by ActiveRecord, or sometimes you need a little more ruby treatment on the value before using it.
10
+
11
+ [This article](https://blog.saeloun.com/2019/10/28/bind-parameters-in-activerecord-sql-queries.html) describe the benefits of using bind parameters with ActiveRecord.
12
+ [This one](https://use-the-index-luke.com/sql/where-clause/bind-parameters) goes further one the subject.
13
+
14
+ The basic idea of this gem is to provide you a way to declare what your query needs as input, what columns it returns and their type. In returns it will allow you to retrieve the rows from result as an array of plain Ruby objects. It will also dynamically creates a class for the row objects that you can customize or can provide it yourself.
15
+
16
+
17
+ NB : This is my very first gem, any suggestions, feedbacks or bug reports are very welcome ! 😃
18
+
19
+ ------
20
+
21
+ ## Installation
22
+
23
+ Add this line to your application's Gemfile:
24
+
25
+ ```ruby
26
+ gem 'wise_gopher'
27
+ ```
28
+
29
+ And then execute:
30
+
31
+ bundle install
32
+
33
+ Or install it yourself as:
34
+
35
+ gem install wise_gopher
36
+
37
+ ------
38
+
39
+ ## Usage
40
+ > DISCLAIMER: for the sake of example, the queries presented here can be very simple and would obviously match an ActiveRecord model. For such queries I would of course highly recommend to use basic ActiveRecord.
41
+ ---
42
+
43
+ To use WiseGopher you have to create a class to declare your query and its specifications. It could look like this:
44
+
45
+ ```ruby
46
+ class PopularArticle < WiseGopher::Base
47
+ query <<-SQL
48
+ SELECT title, AVG(ratings.stars) AS average_rating, published_at, author_username
49
+ FROM articles
50
+ INNER JOIN ratings ON ratings.article_id = articles.id
51
+ WHERE author_username = {{ username }}
52
+ GROUP BY articles.id
53
+ HAVING average_rating > {{ mininum_rating }}
54
+ ORDER BY averating_rating
55
+ SQL
56
+
57
+ param :minimum_rating, :integer
58
+ param :username, :string, transform: :strip
59
+
60
+ row do
61
+ column :title, :string, transform: :capitalize
62
+ column :average_rating, :float, -> { round(2) }
63
+ column :published_at, :datetime
64
+ column :author_username, as: :author
65
+
66
+ def to_s
67
+ "Article '#{title}' by #{author} is rated #{"%.2f" % average_rating}/5."
68
+ end
69
+ end
70
+ end
71
+ ```
72
+
73
+ Which you would use this way:
74
+ ```ruby
75
+ result = PopularArticle.execute_with(minimum_rating: 3, username: "PageHey ")
76
+ # => [#<PopularArticle::Row:0x0000560c37e9de48 @title="My first gem is out!", @average_rating=3.5 ...>, ...]
77
+ puts result.first
78
+ # => Article 'My first gem is out!' by PageHey is rated 3.5/5.
79
+ result.first.class
80
+ # => PopularArticle::Row
81
+ ```
82
+
83
+ ------
84
+
85
+ So, basically what you need to do is make your class inherits from `WiseGopher::Base` and provide your SQL with `.query`. You can then declare what columns will be present in result with `.column` in a block given to `row`.
86
+
87
+
88
+ If your query doesn't need any parameter like this one:
89
+ ```ruby
90
+ class PopularArticle < WiseGopher::Base
91
+ query "SELECT title FROM articles"
92
+
93
+ row do
94
+ column :title, :string
95
+ end
96
+ end
97
+ ```
98
+ You can simply get result with `.execute`:
99
+ ```ruby
100
+ PopularArticle.execute
101
+ ```
102
+
103
+ If your query **does need** parameter like this one:
104
+ ```ruby
105
+ class PopularArticle < WiseGopher::Base
106
+ query <<-SQL
107
+ SELECT title FROM articles
108
+ WHERE author = {{ author_name }} AND published_at > {{ published_after }}
109
+ SQL
110
+
111
+ param :author_name, :string
112
+ param :published_after, :date
113
+
114
+ row do
115
+ column :title, :string
116
+ end
117
+ end
118
+ ```
119
+ You should declare the params with `.param` so you can pass the parameters as a hash to `.execute_with`:
120
+ ```ruby
121
+ PopularArticle.execute_with(author_name: "PageHey", published_after: Date.today - 1.month)
122
+ ```
123
+
124
+ If any parameter is missing or if you call `.execute` for a class that needs some, it will raise `WiseGopher::ArgumentError`.
125
+
126
+ Before query execution, the placeholders will be replaced with the standard `?` placeholder or with the `$1`, `$2` ... numbered placeholders for PostgreSQL database.
127
+
128
+ To declare the column in result, you should use `.row` and pass it a block. Calling this method will create a `Row` class nested into your query class. The block will be then executed in `Row` class context. In this context you can use `.column` but also define method, include module, basicaly write any code you would find in a class delacration.
129
+
130
+ The goal of this syntax is to gather in the same file the input and output logic of the query while keeping dedicated classes for each logic.
131
+ You can provide a custom class to `.row` if you prefer. If you still pass the block to the method, the `WiseGopher::Row` module will be included in the class before evaluating it, so you can have this syntax:
132
+ ```ruby
133
+ _/my_custom_row.rb_
134
+ class MyCustomRow
135
+ def some_custom_method
136
+ # [...]
137
+ end
138
+ end
139
+
140
+ _/my_query_class.rb
141
+ class MyQueryClass < WiseGopher::Base
142
+ query "SELECT title FROM articles"
143
+
144
+ row MyCustomRow do
145
+ column :title, :string
146
+ end
147
+ end
148
+ ```
149
+
150
+ **If you don't give any block to `.row`, make sure you include `WiseGopher::Row` in your class.**
151
+
152
+
153
+ ------
154
+ ## Methods documentation
155
+ ### WiseGopher::Base (class)
156
+ #### .param
157
+ ```ruby
158
+ param(name, type, transform: nil)
159
+ ```
160
+
161
+ Argument | Required | Descrition
162
+ ------------ | ------------- | -------------
163
+ name | true | The name of the parameter as written in the `{{ placeholder }}`
164
+ type | true | The type of the column. It can be any type registred as ActiveRecord::Type. Including yours
165
+ transform: | false | `Proc` or `Symbol`. An operation that will be call before creating the bind parameter when you call `.execute_with`.
166
+
167
+ ### WiseGopher::Row (module)
168
+ #### .column
169
+ ```ruby
170
+ column(name, type, transform: nil, as: nil)
171
+ ```
172
+
173
+ Argument | Required | Descrition
174
+ ------------ | ------------- | -------------
175
+ name | true | The name (or alias) of the SQL column as written in the SELECT statement
176
+ type | true | The type of the column. It can be any type registred as ActiveRecord::Type. Including yours
177
+ transform: | false | `Proc` or `Symbol`. An operation that will be call on value while initializing the row object (See tips below).
178
+ as: | false | The name of the getter you want on the row instance for this column (getter with original name won't be created!)
179
+
180
+ ------
181
+ ## Tips
182
+ #### transform: argument as proc
183
+ If you provide a proc to the `transform:` argument (either on `.column` or `.param`), you can expect one argument or none. If one argument is expected the value of the param or column will be passed.
184
+
185
+ #### Prepare query for later execution
186
+ You can prepare the query with param without executing it by simply calling `.new` on your class and providing the params an later call `.execute`.
187
+ ```ruby
188
+ class PopularArticle < WiseGopher::Base
189
+ query <<-SQL
190
+ SELECT title FROM articles
191
+ WHERE published_at > {{ published_after }}
192
+ SQL
193
+
194
+ param :published_after, :date
195
+
196
+ row do
197
+ column :title, :string
198
+ end
199
+ end
200
+ last_month_articles = PopularArticle.new(published_after: Date.today - 1.month)
201
+ # [...]
202
+ last_month_articles.execute # => [#<PopularArticle::Row:0x0000560c37e9de48 ...>]
203
+ ```
204
+
205
+ #### Ignore column in result
206
+ If for some reason, you have a column in your result that you don't want to retrieve on the row instances, you can use `.ignore`.
207
+ ```ruby
208
+ class MyQuery < WiseGopher::Base
209
+ query "SELECT title, rating FROM articles"
210
+
211
+ row do
212
+ column :title, :string
213
+ ignore :rating
214
+ end
215
+ end
216
+
217
+ MyQuery.execute # => no error raised
218
+ ```
219
+
220
+ ------
221
+
222
+ ## Contributing
223
+
224
+ Bug reports and pull requests are welcome on GitHub at https://github.com/pagehey/wise_gopher. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/pagehey/wise_gopher/blob/master/CODE_OF_CONDUCT.md).
225
+
226
+ ## License
227
+
228
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
229
+
230
+ ## Code of Conduct
231
+
232
+ Everyone interacting in the WiseGopher project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/pagehey/wise_gopher/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "wise_gopher"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ require "pry-doc"
16
+
17
+ require_relative "../spec/database_helper"
18
+
19
+ class Object
20
+ # includes database helpers as top level methods
21
+ include DatabaseHelper
22
+ end
23
+
24
+ IRB.start(__FILE__)
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,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "wise_gopher/version"
4
+ require_relative "wise_gopher/base"
5
+ require_relative "wise_gopher/column"
6
+ require_relative "wise_gopher/param"
7
+ require_relative "wise_gopher/row"
8
+ require_relative "wise_gopher/errors"
9
+
10
+ require "active_record"
11
+
12
+ # base module
13
+ module WiseGopher
14
+ def self.postgresql?
15
+ ActiveRecord::Base.connection.adapter_name.casecmp? "PostgreSQL"
16
+ end
17
+ end
@@ -0,0 +1,166 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+
5
+ module WiseGopher
6
+ # Main inteface of the gem. Class to be inherited by the query class
7
+ class Base
8
+ def self.inherited(base)
9
+ base.class_eval do
10
+ @params = {}
11
+ end
12
+ base.include Methods
13
+ base.extend ClassMethods
14
+ end
15
+
16
+ # class methods for WiseGopher::Base
17
+ module ClassMethods
18
+ attr_reader :row_class, :params
19
+
20
+ def query(query)
21
+ const_set "QUERY", query.freeze
22
+ end
23
+
24
+ def param(name, type, transform = nil)
25
+ param = WiseGopher::Param.new(name, type, transform)
26
+
27
+ params[param.name] = param
28
+ end
29
+
30
+ def row(base = nil, &block)
31
+ @row_class ||= base || define_generic_row_class
32
+
33
+ @row_class.include WiseGopher::Row
34
+
35
+ @row_class.class_eval(&block) if block_given?
36
+ end
37
+
38
+ def execute
39
+ ensure_all_params_are_given
40
+
41
+ new.execute
42
+ end
43
+
44
+ def execute_with(inputs)
45
+ ensure_all_params_are_given(inputs)
46
+
47
+ new(inputs).execute
48
+ end
49
+
50
+ private
51
+
52
+ def define_generic_row_class
53
+ @row_class = const_set "Row", Class.new
54
+ end
55
+
56
+ def ensure_all_params_are_given(inputs = {})
57
+ missing_params = params.keys - inputs.keys.map(&:to_s)
58
+
59
+ raise WiseGopher::ArgumentError, params.slice(*missing_params) if missing_params.any?
60
+ end
61
+ end
62
+
63
+ # instance methods for WiseGopher::Base
64
+ module Methods
65
+ extend ::Forwardable
66
+
67
+ def_delegator :query_class, :row_class
68
+
69
+ def initialize(inputs = {})
70
+ @inputs = inputs
71
+ @binds = []
72
+ @bind_symbol = WiseGopher.postgresql? ? +"$1" : "?"
73
+ @query_prepared = false
74
+
75
+ prepare_query
76
+ end
77
+
78
+ def execute
79
+ ensure_row_class_is_declared
80
+
81
+ result = connection.exec_query(@query.squish, query_class.to_s, @binds, prepare: true)
82
+
83
+ ensure_all_columns_are_declared(result)
84
+
85
+ result.entries.map { |entry| row_class.new(entry) }
86
+ end
87
+
88
+ def prepare_query
89
+ return if @query_prepared
90
+
91
+ @query = query_class::QUERY.dup
92
+
93
+ query_class.params.each do |name, param|
94
+ name = name.to_sym
95
+ value = @inputs[name]
96
+
97
+ bind_params(value, param)
98
+ end
99
+
100
+ @query_prepared = true
101
+ end
102
+
103
+ private
104
+
105
+ def query_class
106
+ self.class
107
+ end
108
+
109
+ def bind_params(value, param)
110
+ if value.is_a? Array
111
+ bind_collection_param(value, param)
112
+ else
113
+ bind_single_param(value, param)
114
+ end
115
+ end
116
+
117
+ def bind_collection_param(values, param)
118
+ bindings = values.map { use_bind_symbol }
119
+
120
+ replace_binding_placeholder(param.name, bindings.join(", "))
121
+
122
+ values.each { |value| register_binding(value, param) }
123
+ end
124
+
125
+ def bind_single_param(value, param)
126
+ replace_binding_placeholder(param.name, use_bind_symbol)
127
+
128
+ register_binding(value, param)
129
+ end
130
+
131
+ def replace_binding_placeholder(name, binding_symbol)
132
+ @query.gsub!(/{{ ?#{name} ?}}/, binding_symbol)
133
+ end
134
+
135
+ def register_binding(value, param)
136
+ @binds << param.build_bind(value)
137
+ end
138
+
139
+ def use_bind_symbol
140
+ if WiseGopher.postgresql?
141
+ symbol = @bind_symbol.dup
142
+
143
+ @bind_symbol.next!
144
+
145
+ symbol
146
+ else
147
+ @bind_symbol
148
+ end
149
+ end
150
+
151
+ def ensure_row_class_is_declared
152
+ raise RowClassIsMissing unless row_class
153
+ end
154
+
155
+ def ensure_all_columns_are_declared(result)
156
+ undeclared_columns = result.columns - row_class.columns.keys - row_class.ignored_columns
157
+
158
+ raise UndeclaredColumns, undeclared_columns if undeclared_columns.any?
159
+ end
160
+
161
+ def connection
162
+ ActiveRecord::Base.connection
163
+ end
164
+ end
165
+ end
166
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WiseGopher
4
+ # Cast query columns and transform value
5
+ class Column
6
+ attr_reader :name, :type, :alias
7
+
8
+ def initialize(name, type_symbol, transform: nil, as: nil)
9
+ @alias = as&.to_s.freeze || name.to_s.freeze
10
+ @name = name.to_s.freeze
11
+ @type = ActiveRecord::Type.lookup type_symbol
12
+ @transform = transform&.to_proc
13
+ end
14
+
15
+ def cast(value)
16
+ casted_value = @type.deserialize(value)
17
+
18
+ @transform ? transform_value(casted_value) : casted_value
19
+ end
20
+
21
+ def define_getter(row_class)
22
+ column = self
23
+
24
+ row_class.define_method(@alias) do
25
+ instance_variable_get(column.instance_variable_name)
26
+ end
27
+ end
28
+
29
+ def instance_variable_name
30
+ @instance_variable_name ||= "@#{@alias.tr("?!", "")}"
31
+ end
32
+
33
+ private
34
+
35
+ def transform_value(value)
36
+ case @transform.arity
37
+ when 0 then value.instance_exec(&@transform)
38
+ else
39
+ value.instance_eval(&@transform)
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WiseGopher
4
+ # Base exception class
5
+ class Error < StandardError; end
6
+
7
+ # raised when `execute` is called whereas query needs params
8
+ # or `execute_with` did not provide all params
9
+ class ArgumentError < Error
10
+ attr_reader :params
11
+
12
+ def initialize(params)
13
+ @params = params.map do |name, param|
14
+ "- \"#{name}\" (#{param.type.type})"
15
+ end.join("\n")
16
+ end
17
+
18
+ def message
19
+ <<~STR
20
+ \n
21
+ The following params are required but were not provided:
22
+ #{params}
23
+ STR
24
+ end
25
+ end
26
+
27
+ # raised when result contains more columns than declared
28
+ class UndeclaredColumns < Error
29
+ attr_reader :column_names
30
+
31
+ def initialize(column_names)
32
+ @column_names = column_names.map do |name|
33
+ "- \"#{name}\""
34
+ end.join("\n")
35
+ end
36
+
37
+ def message
38
+ <<~STR
39
+ \n
40
+ The following columns where found in result but were not declared:
41
+ #{column_names}
42
+
43
+ If you need them during query execution but not in result,
44
+ you should ignore them, like this:
45
+
46
+ class Query < WiseGopher::Base
47
+ query "SELECT title, rating FROM articles"
48
+
49
+ row do
50
+ column :title, :string
51
+ ignore :rating
52
+ end
53
+ end
54
+ STR
55
+ end
56
+ end
57
+
58
+ # raised when row is not declared or not given
59
+ class RowClassIsMissing < Error
60
+ end
61
+
62
+ # raised when custom row class is given but doesn't include WiseGopher::Row
63
+ class RowClassNeedsRowModule < Error
64
+ end
65
+ end
66
+
67
+ # connection;
68
+ # class Query < WiseGopher::Base
69
+ # query "SELECT title, rating FROM articles"
70
+
71
+ # row do
72
+ # column :title, :string
73
+ # end
74
+ # end; Query.execute
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WiseGopher
4
+ # Register query's params and build query's bind variables
5
+ class Param
6
+ attr_reader :name, :type
7
+
8
+ def initialize(name, type_symbol, transform = nil)
9
+ @name = name.to_s.freeze
10
+ @type = ActiveRecord::Type.lookup type_symbol
11
+ @transform = transform&.to_proc
12
+ end
13
+
14
+ def build_bind(value)
15
+ prepared_value = @transform ? transform_value(value) : value
16
+
17
+ ActiveRecord::Relation::QueryAttribute.new(name, prepared_value, type)
18
+ end
19
+
20
+ private
21
+
22
+ def transform_value(value)
23
+ case @transform.arity
24
+ when 0 then value.instance_exec(&@transform)
25
+ else
26
+ value.instance_eval(&@transform)
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WiseGopher
4
+ # This Module handles the declartion of row's columns of query result
5
+ # and defines the getters for row objects
6
+ module Row
7
+ def self.included(base)
8
+ base.class_eval do
9
+ @columns = {}
10
+ @ignored_columns = []
11
+ end
12
+
13
+ base.extend(ClassMethods)
14
+ end
15
+
16
+ # Row class methods
17
+ module ClassMethods
18
+ attr_reader :columns, :ignored_columns
19
+
20
+ def column(name, type, **kwargs)
21
+ column = WiseGopher::Column.new(name, type, **kwargs)
22
+
23
+ column.define_getter(self)
24
+
25
+ columns[column.name] = column
26
+ end
27
+
28
+ def ignore(column_name)
29
+ @ignored_columns << column_name.to_s.freeze
30
+ end
31
+ end
32
+
33
+ def initialize(entry)
34
+ self.class.columns.each do |name, column|
35
+ variable_name = column.instance_variable_name.freeze
36
+
37
+ instance_variable_set(variable_name, column.cast(entry[name]))
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WiseGopher
4
+ module VERSION
5
+ MAJOR = 0
6
+ MINOR = 1
7
+ PATCH = 0
8
+
9
+ STRING = [MAJOR, MINOR, PATCH].join(".")
10
+ end
11
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/wise_gopher/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "wise_gopher"
7
+ spec.version = WiseGopher::VERSION::STRING
8
+ spec.authors = ["PageHey"]
9
+ spec.email = ["pagehey@pm.me"]
10
+
11
+ spec.summary = "Encapsulate raw SQL queries and return result as plain Ruby objects, using ActiveRecord."
12
+ spec.description = <<~STR
13
+ Instead of using `ActiveRecord::Base.connection.execute("some raw sql ...")`,
14
+ use WiseGopher to delcare your queries as classes,
15
+ ensure sql injection protection
16
+ and retrieve results as plain Ruby object with dedicated class instead of raw values in hashes or arrays.
17
+ STR
18
+ spec.homepage = "https://github.com/Pagehey/wise_gopher"
19
+ spec.license = "MIT"
20
+ spec.required_ruby_version = ">= 2.5.0"
21
+
22
+ spec.metadata["homepage_uri"] = spec.homepage
23
+ spec.metadata["source_code_uri"] = "https://github.com/Pagehey/wise_gopher"
24
+ spec.metadata["changelog_uri"] = "https://github.com/Pagehey/wise_gopher/blob/main/CHANGELOG.md"
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
29
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_dependency "activerecord", ">= 5", "< 7"
36
+
37
+ spec.add_development_dependency "database_cleaner", "~> 1.5"
38
+ spec.add_development_dependency "pry"
39
+ spec.add_development_dependency "pry-byebug"
40
+ spec.add_development_dependency "pry-doc"
41
+ spec.add_development_dependency "rake", "~> 13.0"
42
+ spec.add_development_dependency "rspec", "~> 3.10"
43
+ spec.add_development_dependency "rubocop", "~> 1.7"
44
+ spec.add_development_dependency "rubocop-rake"
45
+ spec.add_development_dependency "rubocop-rspec"
46
+ spec.add_development_dependency "sqlite3"
47
+ end
metadata ADDED
@@ -0,0 +1,232 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: wise_gopher
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - PageHey
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-06-29 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: '5'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '7'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '5'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '7'
33
+ - !ruby/object:Gem::Dependency
34
+ name: database_cleaner
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.5'
40
+ type: :development
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1.5'
47
+ - !ruby/object:Gem::Dependency
48
+ name: pry
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ - !ruby/object:Gem::Dependency
62
+ name: pry-byebug
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ - !ruby/object:Gem::Dependency
76
+ name: pry-doc
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ type: :development
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ - !ruby/object:Gem::Dependency
90
+ name: rake
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '13.0'
96
+ type: :development
97
+ prerelease: false
98
+ version_requirements: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '13.0'
103
+ - !ruby/object:Gem::Dependency
104
+ name: rspec
105
+ requirement: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: '3.10'
110
+ type: :development
111
+ prerelease: false
112
+ version_requirements: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - "~>"
115
+ - !ruby/object:Gem::Version
116
+ version: '3.10'
117
+ - !ruby/object:Gem::Dependency
118
+ name: rubocop
119
+ requirement: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - "~>"
122
+ - !ruby/object:Gem::Version
123
+ version: '1.7'
124
+ type: :development
125
+ prerelease: false
126
+ version_requirements: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - "~>"
129
+ - !ruby/object:Gem::Version
130
+ version: '1.7'
131
+ - !ruby/object:Gem::Dependency
132
+ name: rubocop-rake
133
+ requirement: !ruby/object:Gem::Requirement
134
+ requirements:
135
+ - - ">="
136
+ - !ruby/object:Gem::Version
137
+ version: '0'
138
+ type: :development
139
+ prerelease: false
140
+ version_requirements: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ - !ruby/object:Gem::Dependency
146
+ name: rubocop-rspec
147
+ requirement: !ruby/object:Gem::Requirement
148
+ requirements:
149
+ - - ">="
150
+ - !ruby/object:Gem::Version
151
+ version: '0'
152
+ type: :development
153
+ prerelease: false
154
+ version_requirements: !ruby/object:Gem::Requirement
155
+ requirements:
156
+ - - ">="
157
+ - !ruby/object:Gem::Version
158
+ version: '0'
159
+ - !ruby/object:Gem::Dependency
160
+ name: sqlite3
161
+ requirement: !ruby/object:Gem::Requirement
162
+ requirements:
163
+ - - ">="
164
+ - !ruby/object:Gem::Version
165
+ version: '0'
166
+ type: :development
167
+ prerelease: false
168
+ version_requirements: !ruby/object:Gem::Requirement
169
+ requirements:
170
+ - - ">="
171
+ - !ruby/object:Gem::Version
172
+ version: '0'
173
+ description: |
174
+ Instead of using `ActiveRecord::Base.connection.execute("some raw sql ...")`,
175
+ use WiseGopher to delcare your queries as classes,
176
+ ensure sql injection protection
177
+ and retrieve results as plain Ruby object with dedicated class instead of raw values in hashes or arrays.
178
+ email:
179
+ - pagehey@pm.me
180
+ executables: []
181
+ extensions: []
182
+ extra_rdoc_files: []
183
+ files:
184
+ - ".github/workflows/main.yml"
185
+ - ".gitignore"
186
+ - ".rspec"
187
+ - ".rubocop.yml"
188
+ - CHANGELOG.md
189
+ - CODE_OF_CONDUCT.md
190
+ - Gemfile
191
+ - Gemfile.lock
192
+ - LICENSE.txt
193
+ - README.md
194
+ - Rakefile
195
+ - bin/console
196
+ - bin/setup
197
+ - lib/wise_gopher.rb
198
+ - lib/wise_gopher/base.rb
199
+ - lib/wise_gopher/column.rb
200
+ - lib/wise_gopher/errors.rb
201
+ - lib/wise_gopher/param.rb
202
+ - lib/wise_gopher/row.rb
203
+ - lib/wise_gopher/version.rb
204
+ - wise_gopher.gemspec
205
+ homepage: https://github.com/Pagehey/wise_gopher
206
+ licenses:
207
+ - MIT
208
+ metadata:
209
+ homepage_uri: https://github.com/Pagehey/wise_gopher
210
+ source_code_uri: https://github.com/Pagehey/wise_gopher
211
+ changelog_uri: https://github.com/Pagehey/wise_gopher/blob/main/CHANGELOG.md
212
+ post_install_message:
213
+ rdoc_options: []
214
+ require_paths:
215
+ - lib
216
+ required_ruby_version: !ruby/object:Gem::Requirement
217
+ requirements:
218
+ - - ">="
219
+ - !ruby/object:Gem::Version
220
+ version: 2.5.0
221
+ required_rubygems_version: !ruby/object:Gem::Requirement
222
+ requirements:
223
+ - - ">="
224
+ - !ruby/object:Gem::Version
225
+ version: '0'
226
+ requirements: []
227
+ rubygems_version: 3.0.3
228
+ signing_key:
229
+ specification_version: 4
230
+ summary: Encapsulate raw SQL queries and return result as plain Ruby objects, using
231
+ ActiveRecord.
232
+ test_files: []