created_id 1.0.1 → 1.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/CHANGELOG.md +12 -0
- data/README.md +16 -7
- data/VERSION +1 -1
- data/created_id.gemspec +9 -3
- data/lib/created_id/id_range.rb +18 -8
- data/lib/created_id.rb +20 -3
- metadata +12 -9
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: afdabbea09a01fe7c621831292070fdd0138f39ef7efce693745765c5f468fdd
|
4
|
+
data.tar.gz: 6f48cde24728a3f4b92b3c1a003e092f92d4f781e22a68350bb504a210e35f81
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 500a45fdf791907a43d856c4315988343f69ecd571b294cdab0b5f83c347949fafba13e706e0bcfb2951342a96529a2b2d2a62ffc02982269c25f4b88b9c7003
|
7
|
+
data.tar.gz: 5f6ab7875355ffb9f15495c0d0d7ecc83fd01f1a726c734274bc922511a9acdaadcf831b71cc3e0fa3612581a450e4f561d99c0e0b5a87b3b675b99f4087bc69
|
data/CHANGELOG.md
CHANGED
@@ -4,6 +4,18 @@ All notable changes to this project will be documented in this file.
|
|
4
4
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
5
5
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
6
6
|
|
7
|
+
## 1.1.0
|
8
|
+
|
9
|
+
### Changed
|
10
|
+
|
11
|
+
- Omit id clause in queries if ids have not been indexed.
|
12
|
+
- Update queries to use ranges to better support prepared statements.
|
13
|
+
|
14
|
+
### Removed
|
15
|
+
|
16
|
+
- Drop support for ActiveRecord 5.
|
17
|
+
- Drop support for Ruby 2.5 and 2.6.
|
18
|
+
|
7
19
|
## 1.0.1
|
8
20
|
|
9
21
|
### Changed
|
data/README.md
CHANGED
@@ -5,7 +5,13 @@
|
|
5
5
|
[![Ruby Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://github.com/testdouble/standard)
|
6
6
|
[![Gem Version](https://badge.fury.io/rb/created_id.svg)](https://badge.fury.io/rb/created_id)
|
7
7
|
|
8
|
-
|
8
|
+
**CreatedId** optimizes queries on large ActiveRecord tables by precalculating ID ranges for specific time intervals. This lets you avoid full table scans and makes filtering by `created_at` more efficient, even in complex queries.
|
9
|
+
|
10
|
+
### Key Benefits
|
11
|
+
|
12
|
+
- **Efficient Range Queries**: Filter by time-based ID ranges instead of relying on a less predictable `created_at` index.
|
13
|
+
- **Reduced Indexing Needs**: Avoid adding specific `created_at` indexes, letting primary key indexing handle range queries.
|
14
|
+
- **Simple Integration**: Just include the `CreatedId` module in your models and run a periodic task to index ID ranges.
|
9
15
|
|
10
16
|
The use case this code is designed to solve is when you have a large table with an auto-populated `created_at` column where you want to run queries that filter on that column. In most cases, simply adding an index on the `created_at` column will work just fine., However, once you start constructing more complex queries or adding joins and your table grows very large, the index can become less effective and not even be used at all.
|
11
17
|
|
@@ -54,7 +60,7 @@ WHERE tasks.status = 'completed'
|
|
54
60
|
AND tasks.created_at < ?
|
55
61
|
```
|
56
62
|
|
57
|
-
The query optimizer will have
|
63
|
+
The query optimizer will have its choice of several indexes to use to figure out the best query plan. The most important choice will be the first step of the plan to reduce the number of rows that the query needs to look at. Depending on the shape of your data, the query optimizer may decide to simply filter by `status` or `user_id` and then perform a table scan on all the rows to filter by `created_at`, not using the index on that column at all.
|
58
64
|
|
59
65
|
This gem solves for this case by keeping track of the range ids created in each hour in a separate table. When you query on the `created_at` column, it will then look up the possible id range and add that to the query, so the SQL becomes:
|
60
66
|
|
@@ -70,16 +76,16 @@ WHERE tasks.status = 'completed'
|
|
70
76
|
AND tasks.id < ?
|
71
77
|
```
|
72
78
|
|
73
|
-
Because the `id` column is the primary key, it will always be indexed and the query optimizer will generally make better decisions about how to filter the query rows. You won't even need the index on `created_at` since the
|
79
|
+
Because the `id` column is the primary key, it will always be indexed and the query optimizer will generally make better decisions about how to filter the query rows. You won't even need the index on `created_at` since the primary key would always be preferred.
|
74
80
|
|
75
81
|
Another good use case is if you have some periodic tasks to calculate daily stats for some large tables. You will be able to make these queries more efficient without having to add an index on the `created_at` column that's only used on one query per day.
|
76
82
|
|
77
83
|
## Usage
|
78
84
|
|
79
|
-
Run the generator to create the database table
|
85
|
+
Run the generator to create the database migration. This will create a table to store time indexed id ranges for your models.
|
80
86
|
|
81
87
|
```
|
82
|
-
|
88
|
+
rails created_id_engine:install:migrations
|
83
89
|
```
|
84
90
|
|
85
91
|
Next, include the `CreatedId` module into your models. Note that any model you wish to include this module in must have a numeric primary key. If the model is subclassed you will need to include the `CreatedId` module in the parent model.
|
@@ -95,11 +101,14 @@ end
|
|
95
101
|
Now when you want to query by a range on the `created_at` column, you can use the `created_after`, `created_before`, or `created_between` scopes on the model.
|
96
102
|
|
97
103
|
```ruby
|
104
|
+
# Query for tasks completed after a specific time
|
98
105
|
Task.where(status: "completed").created_after(24.hours.ago)
|
99
106
|
|
107
|
+
# Query for tasks by a specific user created before a specific time
|
100
108
|
Task.where(user_id: 1000).created_before(7.days.ago)
|
101
109
|
|
102
|
-
|
110
|
+
# Query for tasks within a specific timeframe
|
111
|
+
Task.created_between(25.hours.ago, 24.hours.ago)
|
103
112
|
```
|
104
113
|
|
105
114
|
You'll then need to set up a periodic task to store the id ranges for your models. For each model that includes `CreatedId`, you need to run the `index_ids_for` once per hour. This task should be run shortly after the top of the hour.
|
@@ -119,7 +128,7 @@ while time < Time.now
|
|
119
128
|
end
|
120
129
|
```
|
121
130
|
|
122
|
-
|
131
|
+
If an ID range is missing for a specific hour, your queries will still function, but with a broader range of IDs. You can recalculate missing ranges at any time to improve efficiency.
|
123
132
|
|
124
133
|
There is an additional requirement for using this gem that you do not change the `created_at` value after a row is inserted since this can mess up the assumption about the correlation between ids and `created_at` timestamps. An error will be thrown if you try to change a record's timestamp after the id range has been created. The query logic can handle small variations between id order and timestamp order (i.e. if id 1000 has a timestamp a few seconds after id 1001).
|
125
134
|
|
data/VERSION
CHANGED
@@ -1 +1 @@
|
|
1
|
-
1.0
|
1
|
+
1.1.0
|
data/created_id.gemspec
CHANGED
@@ -4,10 +4,16 @@ Gem::Specification.new do |spec|
|
|
4
4
|
spec.authors = ["Brian Durand"]
|
5
5
|
spec.email = ["bbdurand@gmail.com"]
|
6
6
|
|
7
|
-
spec.summary = "
|
7
|
+
spec.summary = "Optimize ActiveRecord queries for filtering large tables on the created_at column by pre-computing id ranges."
|
8
8
|
spec.homepage = "https://github.com/bdurand/created_id"
|
9
9
|
spec.license = "MIT"
|
10
10
|
|
11
|
+
spec.metadata = {
|
12
|
+
"homepage_uri" => spec.homepage,
|
13
|
+
"source_code_uri" => spec.homepage,
|
14
|
+
"changelog_uri" => "#{spec.homepage}/blob/main/CHANGELOG.md"
|
15
|
+
}
|
16
|
+
|
11
17
|
# Specify which files should be added to the gem when it is released.
|
12
18
|
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
13
19
|
ignore_files = %w[
|
@@ -26,9 +32,9 @@ Gem::Specification.new do |spec|
|
|
26
32
|
|
27
33
|
spec.require_paths = ["lib"]
|
28
34
|
|
29
|
-
spec.add_dependency "activerecord", ">=
|
35
|
+
spec.add_dependency "activerecord", ">= 6.0"
|
30
36
|
|
31
37
|
spec.add_development_dependency "bundler"
|
32
38
|
|
33
|
-
spec.required_ruby_version = ">= 2.
|
39
|
+
spec.required_ruby_version = ">= 2.7"
|
34
40
|
end
|
data/lib/created_id/id_range.rb
CHANGED
@@ -7,8 +7,8 @@ module CreatedId
|
|
7
7
|
self.table_name = "created_ids"
|
8
8
|
|
9
9
|
scope :for_class, ->(klass) { where(class_name: klass.base_class.name) }
|
10
|
-
scope :created_before, ->(time) { where(
|
11
|
-
scope :created_after, ->(time) { where(
|
10
|
+
scope :created_before, ->(time) { where(hour: nil..time) }
|
11
|
+
scope :created_after, ->(time) { where(hour: time...nil) }
|
12
12
|
|
13
13
|
before_validation :set_hour
|
14
14
|
|
@@ -23,20 +23,30 @@ module CreatedId
|
|
23
23
|
#
|
24
24
|
# @param klass [Class] The class to get the minimum id for.
|
25
25
|
# @param time [Time] The hour to get the minimum id for.
|
26
|
-
# @
|
27
|
-
|
28
|
-
|
26
|
+
# @param allow_nil [Boolean] Whether to allow a nil value to be returned. If this is false,
|
27
|
+
# then the method will return 0 if no value is found.
|
28
|
+
# @return [Integer, nil] The minimum id for the class created in the given hour.
|
29
|
+
def min_id(klass, time, allow_nil: false)
|
30
|
+
return nil if time.nil? && allow_nil
|
31
|
+
|
32
|
+
id = for_class(klass).created_before(time).order(hour: :desc).first&.min_id
|
33
|
+
id ||= 0 unless allow_nil
|
34
|
+
id
|
29
35
|
end
|
30
36
|
|
31
37
|
# Get the maximum id for a class created in a given hour.
|
32
38
|
#
|
33
39
|
# @param klass [Class] The class to get the maximum id for.
|
34
40
|
# @param time [Time] The hour to get the maximum id for.
|
35
|
-
# @
|
36
|
-
|
41
|
+
# @param allow_nil [Boolean] Whether to allow a nil value to be returned. If this is false,
|
42
|
+
# then the method will return the maximum possible id for the id column.
|
43
|
+
# @return [Integer, nil] The maximum id for the class created in the given hour.
|
44
|
+
def max_id(klass, time, allow_nil: false)
|
45
|
+
return nil if time.nil? && allow_nil
|
46
|
+
|
37
47
|
id = for_class(klass).created_after(CreatedId.coerce_hour(time)).order(hour: :asc).first&.max_id
|
38
48
|
|
39
|
-
|
49
|
+
if id.nil? && !allow_nil
|
40
50
|
col_limit = klass.columns.detect { |c| c.name == klass.primary_key }.limit
|
41
51
|
id = if col_limit && col_limit > 0
|
42
52
|
((256**col_limit) / 2) - 1
|
data/lib/created_id.rb
CHANGED
@@ -24,9 +24,8 @@ module CreatedId
|
|
24
24
|
raise ArgmentError, "CreatedId can only be included in ActiveRecord models"
|
25
25
|
end
|
26
26
|
|
27
|
-
scope :created_after, ->(time) {
|
28
|
-
scope :created_before, ->(time) {
|
29
|
-
scope :created_between, ->(time_1, time_2) { created_after(time_1).created_before(time_2) }
|
27
|
+
scope :created_after, ->(time) { created_between(time, nil) }
|
28
|
+
scope :created_before, ->(time) { created_between(nil, time) }
|
30
29
|
|
31
30
|
before_save :verify_created_at_created_id!, if: :created_at_changed?
|
32
31
|
end
|
@@ -42,6 +41,24 @@ module CreatedId
|
|
42
41
|
CreatedId::IdRange.save_created_id(self, time, min_id, max_id)
|
43
42
|
end
|
44
43
|
end
|
44
|
+
|
45
|
+
# Get records created in the given time range. The time range is based on the
|
46
|
+
# created_at column and is inclusive of the start time and exclusive of the end time.
|
47
|
+
#
|
48
|
+
# @param start_time [Time, nil] The start of the time range. If nil, the range is open-ended.
|
49
|
+
# @param end_time [Time, nil] The end of the time range. If nil, the range is open-ended.
|
50
|
+
# @return [ActiveRecord::Relation] The records created in the given time range.
|
51
|
+
def created_between(start_time, end_time)
|
52
|
+
finder = where(created_at: start_time...end_time)
|
53
|
+
|
54
|
+
min_id = CreatedId::IdRange.min_id(self, start_time, allow_nil: true)
|
55
|
+
max_id = CreatedId::IdRange.max_id(self, end_time, allow_nil: true)
|
56
|
+
if min_id || max_id
|
57
|
+
finder = finder.where(primary_key => min_id..max_id)
|
58
|
+
end
|
59
|
+
|
60
|
+
finder
|
61
|
+
end
|
45
62
|
end
|
46
63
|
|
47
64
|
private
|
metadata
CHANGED
@@ -1,14 +1,14 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: created_id
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 1.0
|
4
|
+
version: 1.1.0
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- Brian Durand
|
8
8
|
autorequire:
|
9
9
|
bindir: bin
|
10
10
|
cert_chain: []
|
11
|
-
date: 2024-
|
11
|
+
date: 2024-11-13 00:00:00.000000000 Z
|
12
12
|
dependencies:
|
13
13
|
- !ruby/object:Gem::Dependency
|
14
14
|
name: activerecord
|
@@ -16,14 +16,14 @@ dependencies:
|
|
16
16
|
requirements:
|
17
17
|
- - ">="
|
18
18
|
- !ruby/object:Gem::Version
|
19
|
-
version: '
|
19
|
+
version: '6.0'
|
20
20
|
type: :runtime
|
21
21
|
prerelease: false
|
22
22
|
version_requirements: !ruby/object:Gem::Requirement
|
23
23
|
requirements:
|
24
24
|
- - ">="
|
25
25
|
- !ruby/object:Gem::Version
|
26
|
-
version: '
|
26
|
+
version: '6.0'
|
27
27
|
- !ruby/object:Gem::Dependency
|
28
28
|
name: bundler
|
29
29
|
requirement: !ruby/object:Gem::Requirement
|
@@ -58,7 +58,10 @@ files:
|
|
58
58
|
homepage: https://github.com/bdurand/created_id
|
59
59
|
licenses:
|
60
60
|
- MIT
|
61
|
-
metadata:
|
61
|
+
metadata:
|
62
|
+
homepage_uri: https://github.com/bdurand/created_id
|
63
|
+
source_code_uri: https://github.com/bdurand/created_id
|
64
|
+
changelog_uri: https://github.com/bdurand/created_id/blob/main/CHANGELOG.md
|
62
65
|
post_install_message:
|
63
66
|
rdoc_options: []
|
64
67
|
require_paths:
|
@@ -67,16 +70,16 @@ required_ruby_version: !ruby/object:Gem::Requirement
|
|
67
70
|
requirements:
|
68
71
|
- - ">="
|
69
72
|
- !ruby/object:Gem::Version
|
70
|
-
version: '2.
|
73
|
+
version: '2.7'
|
71
74
|
required_rubygems_version: !ruby/object:Gem::Requirement
|
72
75
|
requirements:
|
73
76
|
- - ">="
|
74
77
|
- !ruby/object:Gem::Version
|
75
78
|
version: '0'
|
76
79
|
requirements: []
|
77
|
-
rubygems_version: 3.4.
|
80
|
+
rubygems_version: 3.4.10
|
78
81
|
signing_key:
|
79
82
|
specification_version: 4
|
80
|
-
summary:
|
81
|
-
|
83
|
+
summary: Optimize ActiveRecord queries for filtering large tables on the created_at
|
84
|
+
column by pre-computing id ranges.
|
82
85
|
test_files: []
|