Created
April 3, 2021 19:46
-
-
Save paracycle/fb222347d14b2719ce6da30ecd614922 to your computer and use it in GitHub Desktop.
Rails 7 Async Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "bundler/inline" | |
gemfile(false) do | |
source "https://rubygems.org" | |
git_source(:github) { |repo| "https://github.com/#{repo}.git" } | |
gem "activerecord", github: "rails/rails" | |
gem 'benchmark-ips' | |
gem "sqlite3" | |
gem "zip" | |
gem "colorize" | |
end | |
require 'active_record' | |
require 'logger' | |
require 'benchmark/ips' | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Base.logger = Logger.new(nil) | |
ActiveRecord::Migration.suppress_messages do | |
ActiveRecord::Schema.define do | |
create_table :posts, if_not_exists: true do |t| | |
t.string :title | |
end | |
create_table :categories, if_not_exists: true do |t| | |
t.string :title | |
end | |
end | |
end | |
class Post < ActiveRecord::Base; end | |
class Category < ActiveRecord::Base; end | |
puts "### Seed DB" | |
Post.delete_all | |
1_000.times { |i| Post.create(title: "Post ##{i}") } | |
Category.delete_all | |
1_000.times { |i| Category.create(title: "Post ##{i}") } | |
def sync_action(count) | |
puts "--> Sync: Entering".colorize(:red) | |
@posts = Post.all.limit(count) | |
@categories = Category.all.limit(count) | |
puts "--> Sync: Starting to enumerate".colorize(:red) | |
puts "=== Got #{@posts.each.count} posts".colorize(:yellow) | |
puts "=== Got #{@categories.each.count} categories".colorize(:yellow) | |
puts "--> Sync Leaving".colorize(:red) | |
end | |
def async_action(count) | |
puts "--> Async: Entering".colorize(:green) | |
@posts = Post.all.limit(count).load_async | |
@categories = Category.all.limit(count).load_async | |
puts "--> Async: Starting to enumerate".colorize(:green) | |
puts "=== Got #{@posts.each.count} posts".colorize(:yellow) | |
puts "=== Got #{@categories.each.count} categories".colorize(:yellow) | |
puts "--> Async: Leaving".colorize(:green) | |
end | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
puts "" | |
puts "### Making Sync Queries" | |
puts "" | |
sync_action(50) | |
puts "" | |
puts "### Making Async Queries" | |
puts "" | |
async_action(50) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment