busload 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b5ce9146375a0bccfc5c4dd30fff9ebcff803353ae9b2cd7bfb65cb8cf02c08d
4
+ data.tar.gz: 2461e6d139e75fbc8d9c436321d50596f082e5c9de6367d8314ae9f7b12f6bf3
5
+ SHA512:
6
+ metadata.gz: b43fcfc80582658d1d80272ca0f948548b1526522bcd0e3098c4ce63bfb49f03bff0726eb085f374c4a5c069dde9f9d0f7da0ca63c8791a302def651fc8e346f
7
+ data.tar.gz: 95e7a1f34d090c05ae61472b4ca7f981b451758caf8ed00e58b1348fad1015c4a786085c6e9afae267cc17ccf2e64deecf4ae8969cab4fefe412f6a569a524a9
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
+ /Gemfile.lock
10
+ /mise.toml
11
+ /gemfiles/*.lock
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-11-30
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Jason Dougherty
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,178 @@
1
+ # Busload
2
+
3
+ Many Active Record queries, one round trip
4
+
5
+ <p align="center"><img src=".github/busload.svg" width="380" alt="A yellow bus full of small, smiling passengers"></p>
6
+
7
+ ## Requirements
8
+
9
+ - Ruby 3.3+
10
+ - Active Record 7.2+
11
+ - PostgreSQL, with the `pg` gem
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application’s Gemfile:
16
+
17
+ ```ruby
18
+ gem "busload"
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### Loading
24
+
25
+ `busload` works like `preload`, but the relation loads with its preloads in one query, instead of one per association. It chains like any relation, and loads when its records are first needed:
26
+
27
+ ```ruby
28
+ users = User.active.busload(posts: :comments).order(:name)
29
+ users.each { ... } # one query
30
+ ```
31
+
32
+ ```sql
33
+ WITH
34
+ "busload_0" AS (
35
+ SELECT users.*
36
+ FROM users
37
+ WHERE active
38
+ ORDER BY name
39
+ ),
40
+ "busload_0/posts" AS (
41
+ SELECT posts.*
42
+ FROM posts
43
+ WHERE user_id IN (SELECT id FROM "busload_0")
44
+ ),
45
+ "busload_0/posts/comments" AS (
46
+ SELECT comments.*
47
+ FROM comments
48
+ WHERE post_id IN (SELECT id FROM "busload_0/posts")
49
+ )
50
+ SELECT 0, t::text FROM "busload_0" t
51
+ UNION ALL SELECT 1, t::text FROM "busload_0/posts" t
52
+ UNION ALL SELECT 2, t::text FROM "busload_0/posts/comments" t
53
+ ```
54
+
55
+ Works on associations too:
56
+
57
+ ```ruby
58
+ user.posts.busload(:comments)
59
+ ```
60
+
61
+ #### Several relations
62
+
63
+ `Busload.load` loads several relations in one query, instead of one each, and returns them in order. Each can have its own preloads:
64
+
65
+ ```ruby
66
+ users, posts, tags = Busload.load(User.active, Post.recent, Tag.popular)
67
+ ```
68
+
69
+ ```sql
70
+ WITH
71
+ "busload_0" AS (SELECT users.* FROM users WHERE active),
72
+ "busload_1" AS (SELECT posts.* FROM posts ORDER BY id DESC LIMIT 10),
73
+ "busload_2" AS (SELECT tags.* FROM tags WHERE popular)
74
+ SELECT 0, t::text FROM "busload_0" t
75
+ UNION ALL SELECT 1, t::text FROM "busload_1" t
76
+ UNION ALL SELECT 2, t::text FROM "busload_2" t
77
+ ```
78
+
79
+ #### preload, includes and eager_load
80
+
81
+ `busload` takes the same arguments as `preload`, and also loads any `preload` or `includes` on the relation:
82
+
83
+ ```ruby
84
+ User.active.busload(:profile, posts: :comments)
85
+ User.active.includes(:profile).busload(:posts)
86
+ ```
87
+
88
+ `eager_load`, and `includes` that becomes a JOIN, stay a JOIN. Preloads under them load separately, so load them with `Busload.load` instead:
89
+
90
+ ```ruby
91
+ Busload.load(User.active.eager_load(:posts), Tag.popular)
92
+ ```
93
+
94
+ #### Records you already have
95
+
96
+ `Busload::Preloader` is a drop-in for `ActiveRecord::Associations::Preloader`, preloading onto records you already have in one query:
97
+
98
+ ```ruby
99
+ Busload::Preloader.new(records: users, associations: { posts: :comments }).call
100
+ ```
101
+
102
+ Like Active Record's, it matches by the records' values in memory and skips associations already loaded. With `scope:`, `available_records:` or `associate_by_default: false`, it hands off to Active Record's preloader.
103
+
104
+ #### Limitations
105
+
106
+ These preloads load afterwards, with Active Record as usual. Busload logs why at debug level:
107
+
108
+ - polymorphic `belongs_to`
109
+ - associations through other associations
110
+ - scopes that take the owner as an argument
111
+ - composite keys
112
+ - preloads under a relation that's eager loaded or has a custom `select`
113
+
114
+ ### Bulk writes
115
+
116
+ Imports and syncs often make several bulk writes in a row, each its own round trip. Buffering sends them in one, as one transaction.
117
+
118
+ `Busload.insert_all`, `insert_all!`, `upsert_all`, `update_all` and `delete_all` take Active Record's arguments, with the model or relation first. Inside `Busload.buffer_writes`, they're held until the block ends, then sent together, in order:
119
+
120
+ ```ruby
121
+ Busload.buffer_writes do
122
+ Busload.insert_all(Post, rows)
123
+ Busload.upsert_all(Tag, tags, unique_by: :name)
124
+ Busload.update_all(User.where(active: false), archived: true)
125
+ Busload.delete_all(Session.where(expires_at: ...Time.current))
126
+ end
127
+ ```
128
+
129
+ ```sql
130
+ INSERT INTO posts ...;
131
+ INSERT INTO tags ... ON CONFLICT (name) DO UPDATE ...;
132
+ UPDATE users SET archived = TRUE WHERE id IN (...);
133
+ DELETE FROM sessions WHERE id IN (...)
134
+ ```
135
+
136
+ Outside a block, they run immediately, like Active Record's.
137
+
138
+ Until the block ends, nothing is written:
139
+
140
+ - Buffered writes return `nil`.
141
+ - Reads in the block don't see them.
142
+ - If the block raises, nothing is written.
143
+ - Blocks can't be nested.
144
+
145
+ `Busload.buffering_writes?` tells you whether you're inside one.
146
+
147
+ To act once the writes are sent, use `Busload.after_flush`. Outside a block, it runs immediately:
148
+
149
+ ```ruby
150
+ class ImportPosts
151
+ def call(rows)
152
+ Busload.insert_all(Post, rows)
153
+ Busload.after_flush { NotifySubscribersJob.perform_later }
154
+ end
155
+ end
156
+
157
+ # Inserts, then enqueues the job
158
+ ImportPosts.new.call(rows)
159
+
160
+ # Enqueues the job once the insert is sent
161
+ Busload.buffer_writes { ImportPosts.new.call(rows) }
162
+ ```
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ docker compose up -d # PostgreSQL on 127.0.0.1:55432
168
+ bundle exec rake # tests and RuboCop
169
+ bin/console # a development database with sample models and data
170
+ ```
171
+
172
+ ## Contributing
173
+
174
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jasondoc3/busload.
175
+
176
+ ## License
177
+
178
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ eval_gemfile "../Gemfile"
4
+
5
+ gem "activerecord", "~> 7.2.0"
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ eval_gemfile "../Gemfile"
4
+
5
+ gem "activerecord", "~> 8.0.0"
6
+ gem "json", "< 3"
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ module Adapters # :nodoc: all
5
+ # The base for every adapter.
6
+ class Base
7
+ def initialize(connection)
8
+ @connection = connection
9
+ end
10
+
11
+ # Runs the CTEs (<tt>name => sql</tt>) as one statement and returns an
12
+ # ActiveRecord::Result per CTE, in order. A CTE's SQL may select from
13
+ # CTEs named before it.
14
+ def select_all(_ctes)
15
+ raise NoMethodError, "#{self.class} must implement select_all"
16
+ end
17
+
18
+ # Runs the write statements, in order, in one round trip.
19
+ def write_all(_statements)
20
+ raise NoMethodError, "#{self.class} must implement write_all"
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ module Adapters # :nodoc: all
5
+ # Builds and runs Busload's statement on PostgreSQL.
6
+ class PostgreSQL < Base
7
+ def select_all(ctes)
8
+ columns = Array.new(ctes.size)
9
+ records = Array.new(ctes.size) { [] }
10
+ @connection.select_rows(statement_for(ctes), "Busload").each do |index, columns_json, record|
11
+ record ? records[index] << record : columns[index] = columns_json
12
+ end
13
+ columns.zip(records).map { |columns_json, cte_records| result_from(columns_json, cte_records) }
14
+ end
15
+
16
+ # Statements sent together run in order, as one transaction.
17
+ def write_all(statements)
18
+ @connection.execute(statements.join(";\n"), "Busload Write All")
19
+ end
20
+
21
+ private
22
+
23
+ # Rows come back in record text format, so values arrive as the strings
24
+ # the adapter normally receives. Each CTE is referenced twice, so Postgres
25
+ # materializes it and keeps its order.
26
+ def statement_for(ctes)
27
+ ctes = ctes.transform_keys { |name| @connection.quote_table_name(name) }
28
+ definitions = ctes.map { |name, sql| "#{name} AS (#{sql})" }
29
+ selects = ctes.keys.each_with_index.flat_map do |name, index|
30
+ [
31
+ "SELECT #{index}, (SELECT json_agg(k) FROM json_object_keys(" \
32
+ "(SELECT row_to_json(t) FROM #{name} t LIMIT 1)) k)::text, NULL::text",
33
+ "SELECT #{index}, NULL, t::text FROM #{name} t"
34
+ ]
35
+ end
36
+
37
+ "WITH #{definitions.join(", ")} #{selects.join(" UNION ALL ")}"
38
+ end
39
+
40
+ def result_from(columns_json, records)
41
+ return ActiveRecord::Result.empty if records.empty?
42
+
43
+ decoder = PG::TextDecoder::Record.new
44
+ ActiveRecord::Result.new(JSON.parse(columns_json), records.map { |record| decoder.decode(record) })
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ # Database-specific code: building and running Busload's statement.
5
+ module Adapters # :nodoc: all
6
+ def self.for(connection)
7
+ if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) &&
8
+ connection.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
9
+ PostgreSQL.new(connection)
10
+ else
11
+ raise Error, "Busload does not support #{connection.adapter_name}"
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ # The writes in a Busload.buffer_writes block, sent together in one round
5
+ # trip when the block ends.
6
+ class Buffer # :nodoc:
7
+ KEY = :busload_buffer
8
+
9
+ def self.current
10
+ ActiveSupport::IsolatedExecutionState[KEY]
11
+ end
12
+
13
+ def self.open
14
+ raise Error, "Busload.buffer_writes blocks can't be nested" if current
15
+
16
+ buffer = ActiveSupport::IsolatedExecutionState[KEY] = new
17
+ begin
18
+ result = yield
19
+ ensure
20
+ ActiveSupport::IsolatedExecutionState.delete(KEY)
21
+ end
22
+ buffer.flush
23
+ result
24
+ end
25
+
26
+ def initialize
27
+ @statements = []
28
+ @after_flush = []
29
+ end
30
+
31
+ def insert_all(target, rows, **)
32
+ return if rows.empty?
33
+
34
+ relation = target.all
35
+ relation.model.with_connection do |connection|
36
+ insert_all = ActiveRecord::InsertAll.new(relation, connection, rows, **)
37
+ add(relation.model, connection.build_insert_sql(ActiveRecord::InsertAll::Builder.new(insert_all)))
38
+ end
39
+ end
40
+
41
+ def update_all(relation, updates)
42
+ model = relation.model
43
+ add(model, "UPDATE #{model.quoted_table_name} SET #{model.sanitize_sql_for_assignment(updates)} " \
44
+ "WHERE #{keys_in(relation)}")
45
+ end
46
+
47
+ def delete_all(relation)
48
+ add(relation.model, "DELETE FROM #{relation.model.quoted_table_name} WHERE #{keys_in(relation)}")
49
+ end
50
+
51
+ def after_flush(&block)
52
+ @after_flush << block
53
+ end
54
+
55
+ def flush
56
+ @model&.with_connection { |connection| Adapters.for(connection).write_all(@statements) }
57
+ @after_flush.each(&:call)
58
+ end
59
+
60
+ private
61
+
62
+ def add(model, sql)
63
+ @model ||= model
64
+ @statements << sql
65
+ nil
66
+ end
67
+
68
+ # Matching rows by key, as a subquery, keeps the relation's joins, order
69
+ # and limit.
70
+ def keys_in(relation)
71
+ model = relation.model
72
+ "#{model.quoted_table_name}.#{model.quoted_primary_key} IN (#{relation.reselect(model.primary_key).to_sql})"
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ # Raised when relations can't be loaded together, such as relations from
5
+ # different databases or on an unsupported adapter.
6
+ class Error < StandardError; end
7
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ class Load # :nodoc: all
5
+ # One CTE in a busload's statement. A CTE with an owner loads one of the
6
+ # owner's associations:
7
+ #
8
+ # SELECT posts.* FROM posts WHERE posts.user_id IN (SELECT id FROM "busload_0")
9
+ class CTE
10
+ attr_reader :relation, :name, :sql
11
+
12
+ # +preloader+ attaches the records to their owners, for a CTE whose
13
+ # owners are already loaded, as with Busload::Preloader.
14
+ def initialize(relation, name, owner: nil, association: nil, preloader: nil)
15
+ @proxy = relation if relation.is_a?(ActiveRecord::Associations::CollectionProxy)
16
+ @relation = @proxy ? @proxy.scope : relation
17
+ @name = name
18
+ @owner = owner
19
+ @association = association
20
+ @preloader = preloader
21
+ @sql = @relation.to_sql
22
+ @join_dependency = join_dependency if @relation.eager_loading?
23
+ end
24
+
25
+ def model
26
+ relation.model
27
+ end
28
+
29
+ def records
30
+ relation.to_a
31
+ end
32
+
33
+ def preload_scope
34
+ ActiveRecord::Relation::StrictLoadingScope if relation.strict_loading_value
35
+ end
36
+
37
+ def cte_for(association)
38
+ table = Arel::Table.new(name)
39
+ relation = association.relation_for(table.project(table[association.reflection.join_foreign_key]))
40
+ CTE.new(relation, "#{name}/#{association.reflection.name}", owner: self, association:)
41
+ end
42
+
43
+ def load(result)
44
+ records = instantiate(result)
45
+ apply_relation_options(records)
46
+ load_relation(records)
47
+ load_proxy(records) if @proxy
48
+ attach(records) if preloader
49
+ end
50
+
51
+ private
52
+
53
+ # Owners load before their associations, so the owner's records are ready.
54
+ def preloader
55
+ @preloader ||= @owner && @association.preloader(@owner.records)
56
+ end
57
+
58
+ def attach(records)
59
+ preloader.load_records(records)
60
+ preloader.run
61
+ end
62
+
63
+ # Built and aliased the same way as the one behind to_sql, so the column
64
+ # aliases match.
65
+ def join_dependency
66
+ associations = relation.eager_load_values | relation.includes_values
67
+ relation.construct_join_dependency(associations, Arel::Nodes::OuterJoin).tap do |join_dependency|
68
+ join_dependency.apply_column_aliases(relation.spawn)
69
+ end
70
+ end
71
+
72
+ def instantiate(result)
73
+ if @join_dependency
74
+ @join_dependency.instantiate(result, relation.strict_loading_value) { |record| assign_inverse(record) }
75
+ else
76
+ result.map { |attributes| model.instantiate(attributes) { |record| assign_inverse(record) } }
77
+ end
78
+ end
79
+
80
+ # Links the record to its owner before its callbacks run, as Active
81
+ # Record does.
82
+ def assign_inverse(record)
83
+ if preloader
84
+ preloader.set_inverse(record)
85
+ elsif relation.is_a?(ActiveRecord::AssociationRelation)
86
+ relation.proxy_association.set_inverse_instance_from_queries(record)
87
+ end
88
+ end
89
+
90
+ def apply_relation_options(records)
91
+ records.each(&:readonly!) if relation.readonly_value
92
+ return if relation.strict_loading_value.nil?
93
+
94
+ records.each { |record| record.strict_loading!(relation.strict_loading_value) }
95
+ end
96
+
97
+ # Relation#load_records is protected.
98
+ def load_relation(records)
99
+ relation.send(:load_records, records)
100
+ end
101
+
102
+ def load_proxy(records)
103
+ @proxy.proxy_association.target = records
104
+ @proxy.proxy_association.loaded!
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ # The CTEs a busload's statement loads, and the preloads left for Active
5
+ # Record to run afterwards.
6
+ class Load # :nodoc: all
7
+ # An association to preload, and the preloads under it.
8
+ Preload = Data.define(:name, :children) do
9
+ # As an argument to Active Record's +preload+.
10
+ def argument
11
+ children.empty? ? name : { name => children.map(&:argument) }
12
+ end
13
+ end
14
+
15
+ # A relation at the top of the statement. +preloader+, when given, is
16
+ # Active Record's preloader that attaches the records to owners already in
17
+ # memory, as with Busload::Preloader.
18
+ Root = Data.define(:relation, :preloader) do
19
+ def initialize(relation:, preloader: nil)
20
+ super
21
+ end
22
+ end
23
+
24
+ def initialize(roots)
25
+ ensure_same_database(roots.map(&:relation))
26
+ @ctes = []
27
+ @deferred = {}
28
+
29
+ roots.each_with_index do |root, index|
30
+ add(CTE.new(root.relation, "busload_#{index}", preloader: root.preloader))
31
+ end
32
+ end
33
+
34
+ def run
35
+ @ctes.first.model.with_connection do |connection|
36
+ ensure_names_fit(connection)
37
+ results = Adapters.for(connection).select_all(@ctes.to_h { |cte| [cte.name, cte.sql] })
38
+ @ctes.zip(results) { |cte, result| cte.load(result) }
39
+ end
40
+
41
+ run_deferred
42
+ end
43
+
44
+ private
45
+
46
+ def ensure_same_database(relations)
47
+ return if relations.map { |relation| relation.model.connection_pool }.uniq.one?
48
+
49
+ raise Error, "Busload can only combine relations that use the same database"
50
+ end
51
+
52
+ def add(cte, nested = [])
53
+ @ctes << cte
54
+ merge_preloads(preloads_for(cte.relation) + nested).each { |preload| add_preload(cte, preload) }
55
+ end
56
+
57
+ def add_preload(owner, preload)
58
+ association = Preloader::Association.new(owner.model, preload.name, owner.preload_scope)
59
+ reason = owner_reason(owner) || association.reason
60
+ return defer(owner, preload, association, reason) if reason
61
+
62
+ add(owner.cte_for(association), preload.children)
63
+ end
64
+
65
+ def defer(owner, preload, association, reason)
66
+ association.log_loads_separately(reason)
67
+ (@deferred[owner] ||= []) << preload
68
+ end
69
+
70
+ # Child CTEs select their keys from the owner's CTE by column name.
71
+ def owner_reason(owner)
72
+ if owner.relation.eager_loading? then "its owner is eager loaded"
73
+ elsif owner.relation.select_values.any? then "its owner has a custom select"
74
+ end
75
+ end
76
+
77
+ # Databases cut off long names, which could make two CTEs share one.
78
+ def ensure_names_fit(connection)
79
+ too_long = @ctes.find { |cte| cte.name.bytesize > connection.max_identifier_length }
80
+ raise Error, "Busload's CTE name #{too_long.name} is too long; preload fewer levels deep" if too_long
81
+ end
82
+
83
+ # Includes that become a JOIN load with the relation, not as preloads.
84
+ def preloads_for(relation)
85
+ return [] if relation.skip_preloading_value
86
+
87
+ associations = relation.preload_values
88
+ associations += relation.includes_values unless relation.eager_loading?
89
+ parse_preloads(associations)
90
+ end
91
+
92
+ def parse_preloads(associations)
93
+ case associations
94
+ when Hash then associations.map { |name, nested| Preload.new(name.to_sym, parse_preloads(nested)) }
95
+ when Array then merge_preloads(associations.flat_map { |nested| parse_preloads(nested) })
96
+ else [Preload.new(associations.to_sym, [])]
97
+ end
98
+ end
99
+
100
+ def merge_preloads(preloads)
101
+ preloads.group_by(&:name).map { |name, same| Preload.new(name, merge_preloads(same.flat_map(&:children))) }
102
+ end
103
+
104
+ def run_deferred
105
+ @deferred.each do |cte, preloads|
106
+ ActiveRecord::Associations::Preloader.new(
107
+ records: cte.records, associations: preloads.map(&:argument), scope: cte.preload_scope
108
+ ).call
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ # Adds .busload to every Active Record model, as Active Record does for
5
+ # +preload+.
6
+ module ModelMethods
7
+ # Calls RelationMethods#busload on +all+.
8
+ def busload(...)
9
+ all.busload(...)
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ class Preloader
5
+ # One association of a model to preload, built on Active Record's preloader
6
+ # for one association.
7
+ class Association # :nodoc:
8
+ attr_reader :reflection
9
+
10
+ def initialize(model, name, scope = nil)
11
+ @model = model
12
+ @name = name
13
+ @reflection = model.reflect_on_association(name)
14
+ @scope = scope
15
+ end
16
+
17
+ # Why Busload can't load the association in SQL, or nil when it can.
18
+ def reason
19
+ if reflection.nil? then "there's no such association"
20
+ elsif reflection.polymorphic? then "it's polymorphic"
21
+ elsif reflection.through_reflection? then "it goes through another association"
22
+ elsif reflection.scope&.arity.to_i.positive? then "its scope depends on the owner"
23
+ elsif reflection.join_foreign_key.is_a?(Array) then "it has a composite key"
24
+ end
25
+ end
26
+
27
+ # Logs, at debug level, that Active Record loads the association instead.
28
+ def log_loads_separately(reason)
29
+ @model.logger&.debug { " #{log_name} #{@model.name}##{@name} loads separately because #{reason}" }
30
+ end
31
+
32
+ # The association's records whose key is in +keys+: a list of values, or
33
+ # an Arel subquery.
34
+ def relation_for(keys)
35
+ key = reflection.klass.arel_table[reflection.join_primary_key]
36
+ preloader([@model.allocate]).scope.where(key.in(keys))
37
+ end
38
+
39
+ # Active Record's preloader for this association on +owners+. Busload
40
+ # links each loaded record to its owner with +set_inverse+ while
41
+ # instantiating it, then attaches the records with +load_records+ and
42
+ # +run+.
43
+ def preloader(owners)
44
+ ActiveRecord::Associations::Preloader::Association.new(reflection.klass, owners, reflection, @scope, nil, true)
45
+ end
46
+
47
+ private
48
+
49
+ # Styled like the names on Active Record's SQL log lines.
50
+ def log_name
51
+ ActiveSupport::LogSubscriber.colorize_logging ? "\e[1m\e[36mBusload\e[0m" : "Busload"
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ # A drop-in for ActiveRecord::Associations::Preloader that preloads in one
5
+ # query:
6
+ #
7
+ # Busload::Preloader.new(records: users, associations: { posts: :comments }).call
8
+ #
9
+ # What it can't load in one query is left to Active Record's preloader.
10
+ class Preloader
11
+ attr_reader :records, :associations, :scope, :associate_by_default
12
+
13
+ def initialize(records:, associations:, scope: nil, available_records: [], associate_by_default: true)
14
+ @records = records
15
+ @associations = associations
16
+ @scope = scope
17
+ @available_records = available_records || []
18
+ @associate_by_default = associate_by_default
19
+ end
20
+
21
+ def empty?
22
+ associations.nil? || records.empty?
23
+ end
24
+
25
+ def call
26
+ return active_record_preloader(records, associations).call unless busloadable?
27
+ return [] if empty?
28
+
29
+ roots = plan
30
+ Load.new(roots).run if roots.any?
31
+ []
32
+ end
33
+
34
+ private
35
+
36
+ def busloadable?
37
+ scope.nil? && @available_records.empty? && associate_by_default
38
+ end
39
+
40
+ # The associations to load, each with the preloader that attaches them to
41
+ # their owners.
42
+ def plan
43
+ records.group_by(&:class).flat_map do |model, owners|
44
+ preloads.filter_map { |name, nested| plan_preload(model, owners, name, nested) }
45
+ end
46
+ end
47
+
48
+ def plan_preload(model, owners, name, nested)
49
+ association = Association.new(model, name)
50
+ if (reason = association.reason)
51
+ association.log_loads_separately(reason)
52
+ active_record_preloader(owners, name => nested).call
53
+ return
54
+ end
55
+
56
+ owners = owners.reject { |owner| owner.association(name).loaded? }
57
+ return if owners.empty?
58
+
59
+ Load::Root.new(relation: relation_for(association, owners, nested), preloader: association.preloader(owners))
60
+ end
61
+
62
+ def relation_for(association, owners, nested)
63
+ keys = owners.filter_map { |owner| owner[association.reflection.join_foreign_key] }.uniq
64
+ relation = association.relation_for(keys)
65
+ nested.empty? ? relation : relation.preload(nested)
66
+ end
67
+
68
+ def preloads
69
+ flatten(associations).group_by(&:first).map do |name, same|
70
+ [name, same.filter_map(&:last)]
71
+ end
72
+ end
73
+
74
+ def flatten(associations)
75
+ case associations
76
+ when Hash then associations.map { |name, nested| [name.to_sym, nested] }
77
+ when Array then associations.flat_map { |nested| flatten(nested) }
78
+ else [[associations.to_sym, nil]]
79
+ end
80
+ end
81
+
82
+ def active_record_preloader(records, associations)
83
+ ActiveRecord::Associations::Preloader.new(
84
+ records:, associations:, scope:, available_records: @available_records, associate_by_default:
85
+ )
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ # Adds #busload to every Active Record relation.
5
+ module RelationMethods
6
+ # Preloads +associations+, like +preload+, and makes the relation load,
7
+ # with every preload it has, in one query.
8
+ #
9
+ # User.active.busload(posts: :comments).order(:name)
10
+ def busload(*associations)
11
+ raise ArgumentError, "The method .busload() must contain arguments." if associations.empty?
12
+
13
+ preload(*associations).extending(Loading)
14
+ end
15
+
16
+ # Loads a relation through Busload.load.
17
+ module Loading # :nodoc:
18
+ def load(&)
19
+ Busload.load(self) unless loaded?
20
+ super
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Busload
4
+ VERSION = "0.1.0"
5
+ end
data/lib/busload.rb ADDED
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "active_record"
5
+ require_relative "busload/version"
6
+ require_relative "busload/errors"
7
+ require_relative "busload/adapters"
8
+ require_relative "busload/adapters/base"
9
+ require_relative "busload/adapters/postgresql"
10
+ require_relative "busload/load"
11
+ require_relative "busload/load/cte"
12
+ require_relative "busload/preloader"
13
+ require_relative "busload/preloader/association"
14
+ require_relative "busload/buffer"
15
+ require_relative "busload/relation_methods"
16
+ require_relative "busload/model_methods"
17
+
18
+ # Busload puts Active Record work that would take many queries into one round
19
+ # trip to the database.
20
+ module Busload
21
+ # Loads every relation, and its preloads, in a single SQL statement and
22
+ # returns them, loaded, in the order given.
23
+ #
24
+ # users, posts = Busload.load(User.active.preload(:posts), Post.recent)
25
+ def self.load(*relations)
26
+ unloaded = relations.reject(&:loaded?)
27
+ Load.new(unloaded.map { |relation| Load::Root.new(relation:) }).run if unloaded.any?
28
+ relations
29
+ end
30
+
31
+ # Holds Busload's writes made in the block, from anywhere in the code it
32
+ # calls, and sends them together, in order, when the block ends. Until then
33
+ # nothing is written, so reads in the block don't see the writes; work that
34
+ # needs them goes in Busload.after_flush. If the block raises, nothing is
35
+ # written.
36
+ #
37
+ # Busload.buffer_writes do
38
+ # Busload.insert_all(Post, rows)
39
+ # Busload.update_all(User.where(active: false), archived: true)
40
+ # end
41
+ def self.buffer_writes(&)
42
+ Buffer.open(&)
43
+ end
44
+
45
+ # Whether writes are being held by Busload.buffer_writes.
46
+ def self.buffering_writes?
47
+ !Buffer.current.nil?
48
+ end
49
+
50
+ # Runs the block after the buffered writes are sent, or right away outside
51
+ # Busload.buffer_writes.
52
+ def self.after_flush(&)
53
+ Buffer.current ? Buffer.current.after_flush(&) : yield
54
+ end
55
+
56
+ # Active Record's +insert_all+, buffered inside Busload.buffer_writes.
57
+ def self.insert_all(target, rows, **)
58
+ return target.insert_all(rows, **) unless Buffer.current
59
+
60
+ Buffer.current.insert_all(target, rows, on_duplicate: :skip, **)
61
+ end
62
+
63
+ # Active Record's +insert_all!+, buffered inside Busload.buffer_writes. A
64
+ # duplicate raises when the buffered writes are sent.
65
+ def self.insert_all!(target, rows, **)
66
+ return target.insert_all!(rows, **) unless Buffer.current
67
+
68
+ Buffer.current.insert_all(target, rows, on_duplicate: :raise, **)
69
+ end
70
+
71
+ # Active Record's +upsert_all+, buffered inside Busload.buffer_writes.
72
+ def self.upsert_all(target, rows, **)
73
+ return target.upsert_all(rows, **) unless Buffer.current
74
+
75
+ Buffer.current.insert_all(target, rows, on_duplicate: :update, **)
76
+ end
77
+
78
+ # Active Record's +update_all+, buffered inside Busload.buffer_writes.
79
+ def self.update_all(relation, updates)
80
+ return relation.update_all(updates) unless Buffer.current
81
+
82
+ Buffer.current.update_all(relation, updates)
83
+ end
84
+
85
+ # Active Record's +delete_all+, buffered inside Busload.buffer_writes.
86
+ def self.delete_all(relation)
87
+ return relation.delete_all unless Buffer.current
88
+
89
+ Buffer.current.delete_all(relation)
90
+ end
91
+ end
92
+
93
+ ActiveSupport.on_load(:active_record) do
94
+ ActiveRecord::Relation.include(Busload::RelationMethods)
95
+ extend Busload::ModelMethods
96
+ end
metadata ADDED
@@ -0,0 +1,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: busload
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jason Dougherty
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activerecord
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.2'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '9'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '7.2'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '9'
32
+ description: 'Busload puts Active Record work that would take many queries into one
33
+ round trip: relations load with their preloads in one statement, and bulk writes
34
+ are sent together.'
35
+ executables: []
36
+ extensions: []
37
+ extra_rdoc_files: []
38
+ files:
39
+ - ".gitignore"
40
+ - CHANGELOG.md
41
+ - LICENSE.txt
42
+ - README.md
43
+ - Rakefile
44
+ - gemfiles/activerecord72.gemfile
45
+ - gemfiles/activerecord80.gemfile
46
+ - lib/busload.rb
47
+ - lib/busload/adapters.rb
48
+ - lib/busload/adapters/base.rb
49
+ - lib/busload/adapters/postgresql.rb
50
+ - lib/busload/buffer.rb
51
+ - lib/busload/errors.rb
52
+ - lib/busload/load.rb
53
+ - lib/busload/load/cte.rb
54
+ - lib/busload/model_methods.rb
55
+ - lib/busload/preloader.rb
56
+ - lib/busload/preloader/association.rb
57
+ - lib/busload/relation_methods.rb
58
+ - lib/busload/version.rb
59
+ homepage: https://github.com/jasondoc3/busload
60
+ licenses:
61
+ - MIT
62
+ metadata:
63
+ source_code_uri: https://github.com/jasondoc3/busload
64
+ changelog_uri: https://github.com/jasondoc3/busload/blob/main/CHANGELOG.md
65
+ rubygems_mfa_required: 'true'
66
+ rdoc_options: []
67
+ require_paths:
68
+ - lib
69
+ required_ruby_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '3.3'
74
+ required_rubygems_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ requirements: []
80
+ rubygems_version: 4.0.20
81
+ specification_version: 4
82
+ summary: Many Active Record queries in one SQL statement
83
+ test_files: []