searchcraft 0.4.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.DS_Store +0 -0
- data/.overcommit.yml +61 -0
- data/.standard.yml +3 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/LICENSE.txt +21 -0
- data/README.md +423 -0
- data/Rakefile +14 -0
- data/lib/search_craft.rb +3 -0
- data/lib/searchcraft/annotate.rb +42 -0
- data/lib/searchcraft/builder.rb +218 -0
- data/lib/searchcraft/configuration.rb +12 -0
- data/lib/searchcraft/depends_on.rb +42 -0
- data/lib/searchcraft/dump_schema.rb +19 -0
- data/lib/searchcraft/model.rb +50 -0
- data/lib/searchcraft/railtie.rb +22 -0
- data/lib/searchcraft/version.rb +5 -0
- data/lib/searchcraft/view_hash_store.rb +61 -0
- data/lib/searchcraft.rb +53 -0
- data/lib/tasks/builders.rake +25 -0
- data/lib/tasks/refresh.rake +12 -0
- data/sig/searchcraft.rbs +4 -0
- metadata +152 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 9b3ce96e5074f0e8664cc1a43c05de1d08d2c95c93e48fec2cc8d5bdb5c6822e
|
4
|
+
data.tar.gz: af503170e6d640853d0d4491019180a86bafbbff0aeedd38424f4053727d4285
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 72fdda7202a5da3c7be085e5ed47a8cc837032698935a9a029a3a7d4f8940ff7a9e048a52cac2777e314b96d4ffd57be971ed976f5bbd8183fbdcee87adf102c
|
7
|
+
data.tar.gz: 9bd38d8a0a60e89b755098c2744c9380843c5898300e6a836f9f70b576da67094b97de3340d01ec777b2e8fcce475a4bc60ff4d00a510b0c7096478b1817aba3
|
data/.DS_Store
ADDED
Binary file
|
data/.overcommit.yml
ADDED
@@ -0,0 +1,61 @@
|
|
1
|
+
# Use this file to configure the Overcommit hooks you wish to use. This will
|
2
|
+
# extend the default configuration defined in:
|
3
|
+
# https://github.com/sds/overcommit/blob/master/config/default.yml
|
4
|
+
#
|
5
|
+
# At the topmost level of this YAML file is a key representing type of hook
|
6
|
+
# being run (e.g. pre-commit, commit-msg, etc.). Within each type you can
|
7
|
+
# customize each hook, such as whether to only run it on certain files (via
|
8
|
+
# `include`), whether to only display output if it fails (via `quiet`), etc.
|
9
|
+
#
|
10
|
+
# For a complete list of hooks, see:
|
11
|
+
# https://github.com/sds/overcommit/tree/master/lib/overcommit/hook
|
12
|
+
#
|
13
|
+
# For a complete list of options that you can use to customize hooks, see:
|
14
|
+
# https://github.com/sds/overcommit#configuration
|
15
|
+
#
|
16
|
+
# Uncomment the following lines to make the configuration take effect.
|
17
|
+
|
18
|
+
verify_signatures: false
|
19
|
+
|
20
|
+
PreCommit:
|
21
|
+
StandardRB:
|
22
|
+
enabled: true
|
23
|
+
required: true
|
24
|
+
command: ['bundle', 'exec', 'standardrb'] # Invoke within Bundler context
|
25
|
+
ErbLint:
|
26
|
+
enabled: true
|
27
|
+
required: true
|
28
|
+
command:
|
29
|
+
[
|
30
|
+
'erblint',
|
31
|
+
'--lint-all',
|
32
|
+
'--enable-linters',
|
33
|
+
'space_around_erb_tag,extra_newline',
|
34
|
+
]
|
35
|
+
# RustyWind:
|
36
|
+
# enabled: true
|
37
|
+
# required: true
|
38
|
+
# command: ['yarn', 'run', 'rustywind-fix']
|
39
|
+
|
40
|
+
# PrePush:
|
41
|
+
# RSpec:
|
42
|
+
# enabled: true
|
43
|
+
# required: true
|
44
|
+
# command: ['bundle', 'exec', 'rspec']
|
45
|
+
|
46
|
+
#PreCommit:
|
47
|
+
# RuboCop:
|
48
|
+
# enabled: true
|
49
|
+
# on_warn: fail # Treat all warnings as failures
|
50
|
+
#
|
51
|
+
# TrailingWhitespace:
|
52
|
+
# enabled: true
|
53
|
+
# exclude:
|
54
|
+
# - '**/db/structure.sql' # Ignore trailing whitespace in generated files
|
55
|
+
#
|
56
|
+
#PostCheckout:
|
57
|
+
# ALL: # Special hook name that customizes all hooks of this type
|
58
|
+
# quiet: true # Change all post-checkout hooks to only display output on failure
|
59
|
+
#
|
60
|
+
# IndexTags:
|
61
|
+
# enabled: true # Generate a tags file with `ctags` each time HEAD changes
|
data/.standard.yml
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 drnicwilliams@gmail.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/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2023 Dr Nic Williams
|
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,423 @@
|
|
1
|
+
<picture>
|
2
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/drnic/searchcraft/blob/develop/docs/searchcraft-logo-white.png?raw=true">
|
3
|
+
<source media="(prefers-color-scheme: light)" srcset="https://github.com/drnic/searchcraft/blob/develop/docs/searchcraft-logo-black.png?raw=true">
|
4
|
+
<img src="https://github.com/drnic/searchcraft/blob/develop/docs/searchcraft-logo-on-white.png?raw=true">
|
5
|
+
</picture>
|
6
|
+
|
7
|
+
Instant search for Rails and ActiveRecord using SQL materialized views.
|
8
|
+
|
9
|
+
* 10x speed improvements to homepages and dashboards
|
10
|
+
* Native Rails replacement for ElasticSearch
|
11
|
+
* Create reporting and summary tables that are easily updatable and queryable
|
12
|
+
|
13
|
+
See [demo app](https://ykdnr.hatchboxapp.com/searchcraft/products?category_id=54) (code found in `demo_app/` folder):
|
14
|
+
|
15
|
+
[![searchcraft 10x speed demo](docs/searchcraft%2010x%20speed%20demo.png)](https://ykdnr.hatchboxapp.com/searchcraft/products?category_id=54)
|
16
|
+
|
17
|
+
## Introduction
|
18
|
+
|
19
|
+
Add lightning quick search capabilities to your Rails apps without external systems like ElasticSearch. It's now magically simple to craft the ActiveRecord/Arel expressions we already know and love, and convert them into SQL materialized views: ready to be queried and composed with ActiveRecord. Everything you love about Rails, but faster.
|
20
|
+
|
21
|
+
**What makes Rails slow for search?** Large tables, lots of joins, subqueries, missing or unused indexes, and complex queries.
|
22
|
+
|
23
|
+
SearchCraft makes it trivial to write and use powerful **SQL materialized views** to pre-calculate the results of your search and reporting queries. It's like a database index, but for complex queries.
|
24
|
+
|
25
|
+
Materialized views are a wonderful feature of PostgreSQL, Oracle, and SQL Server*. They are a table of pre-calculated results of a query. They are fast to query. They are awesome. Like other search systems, you control when you want to refresh them with new data.
|
26
|
+
|
27
|
+
Inside Rails and ActiveRecord, you can access a read-only materialized view like you would any regular table. You can even join them together. You can use them in your ActiveRecord models, scopes, and associations.
|
28
|
+
|
29
|
+
```ruby
|
30
|
+
class ProductSearch < ActiveRecord::Base
|
31
|
+
include SearchCraft::Model
|
32
|
+
end
|
33
|
+
```
|
34
|
+
|
35
|
+
Done. Whatever columns you describe in your view will become attributes on your model.
|
36
|
+
|
37
|
+
If the underlying view had columns `product_id`, `product_name`, `reviews_count`, and `reviews_average`, then you can query it like any other ActiveRecord model:
|
38
|
+
|
39
|
+
```ruby
|
40
|
+
ProductSearch.all
|
41
|
+
[#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
|
42
|
+
#<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
|
43
|
+
#<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]
|
44
|
+
|
45
|
+
ProductSearch.order(reviews_average: :desc)
|
46
|
+
[#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
|
47
|
+
#<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
|
48
|
+
#<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]
|
49
|
+
```
|
50
|
+
|
51
|
+
If you include foreign keys, then you can use `belongs_to` associations. You can add scopes. You can add methods. You can use it as the starting point for queries with the rest of your SQL database. It's just a regular ActiveRecord model.
|
52
|
+
|
53
|
+
All this is already possible with Rails and ActiveRecord. SearchCraft achievement is to make it trivial to live with your materialized views. Trivial to refresh them and to write them.
|
54
|
+
|
55
|
+
### Refresh materialized views
|
56
|
+
|
57
|
+
Each SearchCraft materialized view a snapshot of the results of the query at the time it was created, or last refreshed. It's like a table whose contents are derived from a query.
|
58
|
+
|
59
|
+
If the underlying data to your SearchCraft materialized view changes and you want to refresh it, then call `refresh!` on your model class. This is provided by the `SearchCraft::Model` mixin.
|
60
|
+
|
61
|
+
```ruby
|
62
|
+
ProductSearch.refresh!
|
63
|
+
```
|
64
|
+
|
65
|
+
You can pass this ActiveRecord relation/array to your Rails views and render them. You can join it to other tables and apply further scopes.
|
66
|
+
|
67
|
+
### Writing and iterating on materialized views
|
68
|
+
|
69
|
+
But SearchCraft's greatest feature is help you **write your materialized views**, and then to iterate on them.
|
70
|
+
|
71
|
+
Design them in ActiveRecord expressions, Arel expressions, or even plain SQL. No migrations to rollback and re-run. No keeping track of whether the SQL view in your database matches the SearchCraft code in your Rails app. SearchCraft will automatically create and update your materialized views.
|
72
|
+
|
73
|
+
Update your SearchCraft view, run your tests, they work. Update your SearchCraft view, refresh your development app, and it works. Open up `rails console` and it works; then update your view, type `reload!`, and it works. Deploy to production anywhere, and it works.
|
74
|
+
|
75
|
+
### Write views in ActiveRecord or Arel
|
76
|
+
|
77
|
+
What does it look like to design a materialized view with SearchCraft? For our `ProductSearch` model above, we create a `ProductSearchBuilder` class that inherits from `SearchCraft::Builder` and provides either a `view_scope` method or `view_select_sql` method.
|
78
|
+
|
79
|
+
```ruby
|
80
|
+
class ProductSearchBuilder < SearchCraft::Builder
|
81
|
+
def view_scope
|
82
|
+
Product.where(active: true)
|
83
|
+
.select(
|
84
|
+
"products.id AS product_id",
|
85
|
+
"products.name AS product_name",
|
86
|
+
"(SELECT COUNT(*) FROM product_reviews WHERE product_reviews.product_id = products.id) AS reviews_count",
|
87
|
+
"(SELECT AVG(rating) FROM product_reviews WHERE product_reviews.product_id = products.id) AS reviews_average"
|
88
|
+
)
|
89
|
+
end
|
90
|
+
end
|
91
|
+
```
|
92
|
+
|
93
|
+
The `view_scope` method must return an ActiveRecord relation. It can be as simple or as complex as you like. It can use joins, subqueries, and anything else you can do with ActiveRecord. In the example above we:
|
94
|
+
|
95
|
+
* filter out inactive products
|
96
|
+
* select the `id` and `name` columns from the `products` table; where we can later use `product_id` as a foreign key for joins to the `Product` model in our app
|
97
|
+
* build new `reviews_count` and `reviews_average` columns using SQL subqueries that counts and averages the `rating` column from the `product_reviews` table.
|
98
|
+
|
99
|
+
SearchCraft will convert this into a materialized view, create it into your database, and the `ProductSearch` model above will start using it when you next reload your development app or run your tests. If you make a change, SearchCraft will drop and recreate the view automatically.
|
100
|
+
|
101
|
+
When we load up our app into Rails console, or run our tests, or refresh the development app, the `ProductSearch` model will be automatically updated to match any changes in `ProductSearchBuilder`.
|
102
|
+
|
103
|
+
```ruby
|
104
|
+
ProductSearch.all
|
105
|
+
[#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
|
106
|
+
#<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
|
107
|
+
#<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]
|
108
|
+
|
109
|
+
ProductSearch.order(reviews_average: :desc)
|
110
|
+
[#<ProductSearch product_id: 2, product_name: "iPhone 15", reviews_count: 5, reviews_average: 0.38e1>,
|
111
|
+
#<ProductSearch product_id: 1, product_name: "Laptop 3", reviews_count: 5, reviews_average: 0.28e1>,
|
112
|
+
#<ProductSearch product_id: 4, product_name: "Monopoly", reviews_count: 3, reviews_average: 0.2e1>]
|
113
|
+
```
|
114
|
+
|
115
|
+
### Write views in SQL
|
116
|
+
|
117
|
+
If you want to write SQL, then you can use the `view_select_sql` method instead.
|
118
|
+
|
119
|
+
```ruby
|
120
|
+
class NumberBuilder < SearchCraft::Builder
|
121
|
+
# Write SQL that produces 5 rows, with a 'number' column containing the number of the row
|
122
|
+
def view_select_sql
|
123
|
+
"SELECT generate_series(1, 5) AS number;"
|
124
|
+
end
|
125
|
+
end
|
126
|
+
|
127
|
+
class Number < ActiveRecord::Base
|
128
|
+
include SearchCraft::Model
|
129
|
+
end
|
130
|
+
```
|
131
|
+
|
132
|
+
```ruby
|
133
|
+
Number.all
|
134
|
+
[#<Number number: 1>, #<Number number: 2>, #<Number number: 3>, #<Number number: 4>, #<Number number: 5>]
|
135
|
+
```
|
136
|
+
|
137
|
+
### Dependencies between views
|
138
|
+
|
139
|
+
Once you have one SearchCraft materialized view, you might want to create another that depends upon it. You can do this too with the `depends_on` method.
|
140
|
+
|
141
|
+
```ruby
|
142
|
+
class SquaredBuilder < SearchCraft::Builder
|
143
|
+
depends_on "NumberBuilder"
|
144
|
+
|
145
|
+
def view_select_sql
|
146
|
+
"SELECT number, number * number AS squared FROM #{Number.table_name};"
|
147
|
+
end
|
148
|
+
end
|
149
|
+
|
150
|
+
class Squared < ActiveRecord::Base
|
151
|
+
include SearchCraft::Model
|
152
|
+
end
|
153
|
+
```
|
154
|
+
|
155
|
+
If you make a change to `NumberBuilder`, then SearchCraft will automatically drop and recreate both the `Number` and `Squared` materialized views.
|
156
|
+
|
157
|
+
```ruby
|
158
|
+
Squared.all
|
159
|
+
[#<Squared number: 1, squared: 1>,
|
160
|
+
#<Squared number: 2, squared: 4>,
|
161
|
+
#<Squared number: 3, squared: 9>,
|
162
|
+
#<Squared number: 4, squared: 16>,
|
163
|
+
#<Squared number: 5, squared: 25>]
|
164
|
+
```
|
165
|
+
|
166
|
+
### Use ChatGPT to write your views
|
167
|
+
|
168
|
+
Aren't confident writing complex SQL or Arel expressions? Me either. I ask GPT4 or GitHub Copilot. I explain the nature of my schema and tables, and ask it to write some SQL, and then ask to convert it into Arel. Or I give it a small snippet it of SQL, and ask it to convert it into Arel. I then copy/paste the results into my SearchCraft builder class.
|
169
|
+
|
170
|
+
It is absolutely worth learning to express your search queries in SQL or Arel, and putting them into a SearchCraft materialized view. Your users will have a lightning fast experience.
|
171
|
+
|
172
|
+
### Databases and materialized view support
|
173
|
+
|
174
|
+
* A future version of SearchCraft might implement a similar feature for MySQL by creating simple views and caching the results in tables.
|
175
|
+
* SearchCraft has been developed and tested against PostgreSQL, but it should "just work" for database servers that support materialized views, such as Oracle and SQL Server. Please create tickets if there are issues.
|
176
|
+
|
177
|
+
## Installation
|
178
|
+
|
179
|
+
Inside your Rails app, add the gem to your Gemfile:
|
180
|
+
|
181
|
+
```plain
|
182
|
+
bundle add searchcraft
|
183
|
+
```
|
184
|
+
|
185
|
+
SearchCraft will automatically create an internal DB table that it needs, so there's no database migration to run. And of course, it will automatically create and recreate your materialized views.
|
186
|
+
|
187
|
+
## Learning SearchCraft
|
188
|
+
|
189
|
+
1. Re-read the introduction above.
|
190
|
+
2. Read and run the examples in the [examples/](examples/) folder.
|
191
|
+
3. Look at the Rails app in the [demo_app](demo_app/) folder. It contains models, SearchCraft builders, unit tests, and system tests.
|
192
|
+
4. Follow along this simple tutorial in any of your Rails apps.
|
193
|
+
|
194
|
+
### Tutorial
|
195
|
+
|
196
|
+
Inside any Rails app you can follow along with this tutorial. If you don't have a Rails app, use the app found in `demo_app` folder of this project.
|
197
|
+
|
198
|
+
Install the gem:
|
199
|
+
|
200
|
+
```plain
|
201
|
+
bundle add searchcraft
|
202
|
+
```
|
203
|
+
|
204
|
+
Pick one of your existing application models, say `Product`, and we will create a trivial materialized view for it. Say, we want a fast way to get the top 5 selling products and some details we'll use for it in our HTML view.
|
205
|
+
|
206
|
+
Create a new ActiveRecord model file `app/models/product_latest_arrival.rb`:
|
207
|
+
|
208
|
+
```ruby
|
209
|
+
class ProductLatestArrival < ActiveRecord::Base
|
210
|
+
include SearchCraft::Model
|
211
|
+
end
|
212
|
+
```
|
213
|
+
|
214
|
+
By Rails conventions, this model will look for a SQL table or view called `product_latest_arrivals`. This does not exist yet.
|
215
|
+
|
216
|
+
We can confirm this by opening up `rails console` and trying to query it:
|
217
|
+
|
218
|
+
```ruby
|
219
|
+
ProductLatestArrival.all
|
220
|
+
# ActiveRecord::StatementInvalid ERROR: relation "product_latest_arrivals" does not exist
|
221
|
+
```
|
222
|
+
|
223
|
+
We can create a new SearchCraft builder class to define our materialized view. Create a new file `app/searchcraft/product_latest_arrival_builder.rb`.
|
224
|
+
|
225
|
+
I suggest `app/searchcraft` for your builders, but they can go into any `app/` subfolder that is autoloaded by Rails.
|
226
|
+
|
227
|
+
```ruby
|
228
|
+
class ProductLatestArrivalBuilder < SearchCraft::Builder
|
229
|
+
def view_scope
|
230
|
+
Product.order(created_at: :desc).limit(5)
|
231
|
+
end
|
232
|
+
end
|
233
|
+
```
|
234
|
+
|
235
|
+
Inside your `rails console``, run `reload!` and check your query again:
|
236
|
+
|
237
|
+
```ruby
|
238
|
+
reload!
|
239
|
+
|
240
|
+
ProductLatestArrival.all
|
241
|
+
ProductLatestArrival Load (1.3ms) SELECT "product_latest_arrivals".* FROM "product_latest_arrivals"
|
242
|
+
=>
|
243
|
+
[#<ProductLatestArrival:0x000000010a737d18
|
244
|
+
id: 1,
|
245
|
+
name: "Rustic Wool Coat",
|
246
|
+
active: true,
|
247
|
+
created_at: Fri, 25 Aug 2023 07:15:16.995228000 UTC +00:00,
|
248
|
+
updated_at: Fri, 25 Aug 2023 07:15:16.995228000 UTC +00:00,
|
249
|
+
image_url: "https://loremflickr.com/g/320/320/coat?lock=1">,
|
250
|
+
...
|
251
|
+
```
|
252
|
+
|
253
|
+
If you have the `annotate` gem installed in your `Gemfile`, you will also note that `product_latest_arrival.rb` model has been updated to reflect the columns in the materialized view.
|
254
|
+
|
255
|
+
```ruby
|
256
|
+
# == Schema Information
|
257
|
+
#
|
258
|
+
# Table name: product_latest_arrivals
|
259
|
+
#
|
260
|
+
# id :bigint
|
261
|
+
# name :string
|
262
|
+
# active :boolean
|
263
|
+
# created_at :datetime
|
264
|
+
# updated_at :datetime
|
265
|
+
# image_url :string
|
266
|
+
#
|
267
|
+
class ProductLatestArrival < ActiveRecord::Base
|
268
|
+
include SearchCraft::Model
|
269
|
+
end
|
270
|
+
```
|
271
|
+
|
272
|
+
If your application is under source control, you can also see that `db/schema.rb` has been updated to reflect the latest view definition. Run `git diff db/schema.rb`:
|
273
|
+
|
274
|
+
```ruby
|
275
|
+
create_view "product_latest_arrivals", materialized: true, sql_definition: <<-SQL
|
276
|
+
SELECT products.id,
|
277
|
+
products.name,
|
278
|
+
products.active,
|
279
|
+
products.created_at,
|
280
|
+
products.updated_at,
|
281
|
+
products.image_url
|
282
|
+
FROM products
|
283
|
+
LIMIT 5;
|
284
|
+
SQL
|
285
|
+
```
|
286
|
+
|
287
|
+
You can now continue to change the `view_scope` in your builder, and run `reload!` in rails console to test out your change.
|
288
|
+
|
289
|
+
For example, you can `select()` only the columns that you want using SQL expression for each one:
|
290
|
+
|
291
|
+
```ruby
|
292
|
+
class ProductLatestArrivalBuilder < SearchCraft::Builder
|
293
|
+
def view_scope
|
294
|
+
Product
|
295
|
+
.order(created_at: :desc)
|
296
|
+
.limit(5)
|
297
|
+
.select(
|
298
|
+
"products.id as product_id",
|
299
|
+
"products.name as product_name",
|
300
|
+
"products.image_url as product_image_url",
|
301
|
+
)
|
302
|
+
end
|
303
|
+
end
|
304
|
+
```
|
305
|
+
|
306
|
+
Or you can use Arel expressions to build the SQL:
|
307
|
+
|
308
|
+
```ruby
|
309
|
+
class ProductLatestArrivalBuilder < SearchCraft::Builder
|
310
|
+
def view_scope
|
311
|
+
Product
|
312
|
+
.order(created_at: :desc)
|
313
|
+
.limit(5)
|
314
|
+
.select(
|
315
|
+
Product.arel_table[:id].as("product_id"),
|
316
|
+
Product.arel_table[:name].as("product_name"),
|
317
|
+
Product.arel_table[:image_url].as("product_image_url"),
|
318
|
+
)
|
319
|
+
end
|
320
|
+
end
|
321
|
+
```
|
322
|
+
|
323
|
+
What about data updates? Let's create more `Products`:
|
324
|
+
|
325
|
+
```ruby
|
326
|
+
Product.create!(name: "Starlink")
|
327
|
+
Product.create!(name: "Fishing Rod")
|
328
|
+
```
|
329
|
+
|
330
|
+
If you were to inspect `ProductLatestArrival.all` you would **not find** these new products. This is because the materialized view is a snapshot of the data at the time it was created or last refreshed.
|
331
|
+
|
332
|
+
To refresh the view:
|
333
|
+
|
334
|
+
```ruby
|
335
|
+
ProductLatestArrival.refresh!
|
336
|
+
```
|
337
|
+
|
338
|
+
Alternately, to refresh all views:
|
339
|
+
|
340
|
+
```ruby
|
341
|
+
SearchCraft::Model.refresh_all!
|
342
|
+
```
|
343
|
+
|
344
|
+
And confirm that the latest new arrivals are now in the materialized view:
|
345
|
+
|
346
|
+
```ruby
|
347
|
+
ProductLatestArrival.pluck(:name)
|
348
|
+
=> ["Fishing Rod", "Starlink", "Sleek Steel Bag", "Ergonomic Plastic Bench", "Fantastic Wooden Keyboard"]
|
349
|
+
```
|
350
|
+
|
351
|
+
If you want to remove the artifacts of this tutorial. First, drop the materialized view from your database schema:
|
352
|
+
|
353
|
+
```ruby
|
354
|
+
ProductLatestArrivalBuilder.new.drop_view!
|
355
|
+
```
|
356
|
+
|
357
|
+
Then remove the files and `git checkout .` to revert any other changes.
|
358
|
+
|
359
|
+
```plain
|
360
|
+
rm app/searchcraft/product_latest_arrival_builder.rb
|
361
|
+
rm app/models/product_latest_arrival.rb
|
362
|
+
git checkout db/schema.rb
|
363
|
+
```
|
364
|
+
|
365
|
+
### Rake tasks
|
366
|
+
|
367
|
+
SearchCraft provides two rake tasks:
|
368
|
+
|
369
|
+
* `rake searchcraft:refresh` - refresh all materialized views
|
370
|
+
* `rake searchcraft:rebuild` - check if any views need to be recreated
|
371
|
+
|
372
|
+
To add these to your Rails app, add the following to the bottom of your `Rakefile`:
|
373
|
+
|
374
|
+
```ruby
|
375
|
+
SearchCraft.load_tasks
|
376
|
+
```
|
377
|
+
|
378
|
+
### Features
|
379
|
+
|
380
|
+
* Watches `Builder` subclasses, and automatically detects change to materialize view schema and recreates it
|
381
|
+
* ActiveRecord model mixin to allow `refresh!` of materialized view contents
|
382
|
+
* Dumps `db/schema.rb` whenever materialized view is updated
|
383
|
+
* Annotates models whenever materialized view is updated, if `annotate` gem is installed
|
384
|
+
* Namespaced models/builders will use the full namesapce + classname for the materialized view name
|
385
|
+
* Rake tasks to refresh all materialized views `rake searchcraft:refresh`, and check if any views need to be recreated `rake searchcraft:rebuild`
|
386
|
+
|
387
|
+
## Development
|
388
|
+
|
389
|
+
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.
|
390
|
+
|
391
|
+
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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
392
|
+
|
393
|
+
To bump a version number:
|
394
|
+
|
395
|
+
1. Use the `gem bump` command, e.g. `gem bump -v patch`
|
396
|
+
2. Update the `demo_app/Gemfile.lock`, e.g. `(cd demo_app; bundle)`
|
397
|
+
3. Merge that change back into bump commit, e.g. `git add demo_app/Gemfile.lock; git commit --amend --no-edit`
|
398
|
+
3. Cut a release `rake release`
|
399
|
+
|
400
|
+
```plain
|
401
|
+
gem bump -v patch
|
402
|
+
(cd demo_app; bundle)
|
403
|
+
git add demo_app/Gemfile.lock; git commit --amend --no-edit
|
404
|
+
git push
|
405
|
+
rake release
|
406
|
+
```
|
407
|
+
|
408
|
+
## Contributing
|
409
|
+
|
410
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/drnic/searchcraft. 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/drnic/searchcraft/blob/develop/CODE_OF_CONDUCT.md).
|
411
|
+
|
412
|
+
## License
|
413
|
+
|
414
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
415
|
+
|
416
|
+
## Code of Conduct
|
417
|
+
|
418
|
+
Everyone interacting in the Searchcraft project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/drnic/searchcraft/blob/develop/CODE_OF_CONDUCT.md).
|
419
|
+
|
420
|
+
## Credits
|
421
|
+
|
422
|
+
* [scenic](https://github.com/scenic-views/scenic) gem first allowed me to use materialized views in Rails, but I was iterating on my view schema so frequently that their migration approach - `rails db:rollback`, rebuild migration SQL, `rails db:migrate`, and then test - became slow. It also introduced bugs - I would forget to run the steps, and then see odd behaviour. If you have relatively static views or materialized views, and want to use Rails migrations, please try out `scenic` gem. This `searchcraft` gem still depends on `scenic` for its view `refresh` feature, and adding views into `schema.rb`.
|
423
|
+
* [activerecord](https://github.com/rails/rails) has been one of the most wonderful gifts to the universe since its inception. As a bonus, it allowed me to become "Dr Nic" in 2006 when I performed silly tricks with it in a rubygem called "Dr Nic's Magic Models". I've made many dear friends and had a wonderful career since those days.
|
data/Rakefile
ADDED
@@ -0,0 +1,14 @@
|
|
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
|
+
require "standard/rake"
|
13
|
+
|
14
|
+
task default: %i[test standard]
|
data/lib/search_craft.rb
ADDED
@@ -0,0 +1,42 @@
|
|
1
|
+
module SearchCraft::Annotate
|
2
|
+
extend ActiveSupport::Concern
|
3
|
+
|
4
|
+
# If using annotate gem, then automatically annotate models after rebuilding views
|
5
|
+
# TODO: I'm suspicious this is not working for dependent Builders, e.g. demo_app's OnsaleSearchBuilder
|
6
|
+
def annotate_models!
|
7
|
+
return unless Rails.env.development?
|
8
|
+
return unless Object.const_defined?(:Annotate)
|
9
|
+
|
10
|
+
options = {
|
11
|
+
is_rake: true,
|
12
|
+
position: "before",
|
13
|
+
additional_file_patterns: [],
|
14
|
+
model_dir: "app/models",
|
15
|
+
root_dir: Rails.root.to_s,
|
16
|
+
require: [],
|
17
|
+
exclude_controllers: true,
|
18
|
+
exclude_helpers: true,
|
19
|
+
hide_limit_column_types: "",
|
20
|
+
hide_default_column_types: "",
|
21
|
+
ignore_unknown_models: true
|
22
|
+
}
|
23
|
+
capture_stdout do
|
24
|
+
AnnotateModels.do_annotations(options)
|
25
|
+
end
|
26
|
+
rescue PG::UndefinedTable
|
27
|
+
rescue => e
|
28
|
+
puts "Error annotating models: #{e.message}"
|
29
|
+
pp e.backtrace
|
30
|
+
end
|
31
|
+
|
32
|
+
def capture_stdout(&block)
|
33
|
+
old_stdout = $stdout
|
34
|
+
$stdout = StringIO.new
|
35
|
+
yield
|
36
|
+
if SearchCraft.debug?
|
37
|
+
puts $stdout.string
|
38
|
+
end
|
39
|
+
ensure
|
40
|
+
$stdout = old_stdout
|
41
|
+
end
|
42
|
+
end
|