Busload
Many Active Record queries, one round trip
Requirements
- Ruby 3.3+
- Active Record 7.2+
- PostgreSQL, with the
pggem
Installation
Add this line to your application’s Gemfile:
gem "busload"Usage
Loading
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:
users = User.active.busload(posts: :comments).order(:name)
users.each { ... } # one queryWITH
"busload_0" AS (
SELECT users.*
FROM users
WHERE active
ORDER BY name
),
"busload_0_1" AS (
SELECT posts.*
FROM posts
WHERE user_id IN (SELECT id FROM "busload_0")
),
"busload_0_1_1" AS (
SELECT comments.*
FROM comments
WHERE post_id IN (SELECT id FROM "busload_0_1")
)
SELECT 0, t::text FROM "busload_0" t
UNION ALL SELECT 1, t::text FROM "busload_0_1" t
UNION ALL SELECT 2, t::text FROM "busload_0_1_1" tWorks on associations too:
user.posts.busload(:comments)Several relations
Busload.load loads several relations in one query, instead of one each, and returns them in order. Each can have its own preloads:
users, posts, tags = Busload.load(User.active, Post.recent, Tag.popular)WITH
"busload_0" AS (SELECT users.* FROM users WHERE active),
"busload_1" AS (SELECT posts.* FROM posts ORDER BY id DESC LIMIT 10),
"busload_2" AS (SELECT tags.* FROM tags WHERE popular)
SELECT 0, t::text FROM "busload_0" t
UNION ALL SELECT 1, t::text FROM "busload_1" t
UNION ALL SELECT 2, t::text FROM "busload_2" tpreload, includes and eager_load
busload takes the same arguments as preload, and also loads any preload or includes on the relation:
User.active.busload(:profile, posts: :comments)
User.active.includes(:profile).busload(:posts)eager_load, and includes that becomes a JOIN, stay a JOIN. Preloads under them load separately, so load them with Busload.load instead:
Busload.load(User.active.eager_load(:posts), Tag.popular)Records you already have
Busload::Preloader is a drop-in for ActiveRecord::Associations::Preloader, preloading onto records you already have in one query:
Busload::Preloader.new(records: users, associations: { posts: :comments }).callLike 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.
Limitations
These preloads load afterwards, with Active Record as usual. Busload logs why at debug level:
- polymorphic
belongs_to - associations through other associations
- scopes that take the owner as an argument
- composite keys
- keys whose column types differ, like a
uuidid and avarcharforeign key - preloads under a relation that's eager loaded or has a custom
select
Bulk writes
Imports and syncs often make several bulk writes in a row, each its own round trip. Buffering sends them in one, as one transaction.
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:
Busload.buffer_writes do
Busload.insert_all(Post, rows)
Busload.upsert_all(Tag, tags, unique_by: :name)
Busload.update_all(User.where(active: false), archived: true)
Busload.delete_all(Session.where(expires_at: ...Time.current))
endINSERT INTO posts ...;
INSERT INTO tags ... ON CONFLICT (name) DO UPDATE ...;
UPDATE users SET archived = TRUE WHERE id IN (...);
DELETE FROM sessions WHERE id IN (...)Outside a block, they run immediately, like Active Record's.
Until the block ends, nothing is written:
- Buffered writes return
nil. - Reads in the block don't see them.
- If the block raises, nothing is written.
- Blocks can't be nested.
Busload.buffering_writes? tells you whether you're inside one.
To act once the writes are sent, use Busload.after_flush. Outside a block, it runs immediately:
class ImportPosts
def call(rows)
Busload.insert_all(Post, rows)
Busload.after_flush { NotifySubscribersJob.perform_later }
end
end
# Inserts, then enqueues the job
ImportPosts.new.call(rows)
# Enqueues the job once the insert is sent
Busload.buffer_writes { ImportPosts.new.call(rows) }Development
docker compose up -d # PostgreSQL on 127.0.0.1:55432
bundle exec rake # tests and RuboCop
bin/console # a development database with sample models and dataContributing
Bug reports and pull requests are welcome on GitHub at https://github.com/jasondoc3/busload.
License
The gem is available as open source under the terms of the MIT License.