├── .ruby-version
├── lib
├── fast_page
│ ├── version.rb
│ ├── active_record_extension.rb
│ └── active_record_methods.rb
└── fast_page.rb
├── .gitignore
├── bin
├── setup
└── console
├── Gemfile
├── Rakefile
├── .github
└── workflows
│ ├── main.yml
│ └── licensing.yml
├── .rubocop.yml
├── doc
└── dependency_decisions.yml
├── test
├── test_helper.rb
├── kaminari_test.rb
├── pagy_test.rb
└── fast_page_test.rb
├── fast_page.gemspec
├── Gemfile.lock
├── CODE_OF_CONDUCT.md
├── README.md
└── LICENSE
/.ruby-version:
--------------------------------------------------------------------------------
1 | 3.1.2
2 |
--------------------------------------------------------------------------------
/lib/fast_page/version.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | module FastPage
4 | VERSION = "0.1.7"
5 | end
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.bundle/
2 | /.yardoc
3 | /_yardoc/
4 | /coverage/
5 | /pkg/
6 | /spec/reports/
7 | /tmp/
8 | *.gem
9 |
10 |
--------------------------------------------------------------------------------
/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -euo pipefail
3 | IFS=$'\n\t'
4 | set -vx
5 |
6 | bundle install
7 |
8 | # Do any other automated setup that you need to do here
9 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | source "https://rubygems.org"
4 |
5 | # Specify your gem's dependencies in fast_page.gemspec
6 | gemspec
7 |
8 | gem "rake", "~> 13.0"
9 |
10 | gem "rubocop", "~> 1.7"
11 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "rake/testtask"
4 | require "bundler/gem_tasks"
5 | require "rubocop/rake_task"
6 |
7 | RuboCop::RakeTask.new
8 |
9 | Rake::TestTask.new do |t|
10 | t.pattern = "test/*_test.rb"
11 | end
12 |
13 | task default: %i[test rubocop]
14 |
--------------------------------------------------------------------------------
/lib/fast_page.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "active_support/lazy_load_hooks"
4 | require_relative "fast_page/version"
5 | require_relative "fast_page/active_record_extension"
6 |
7 | ActiveSupport.on_load :active_record do
8 | ::ActiveRecord::Base.include FastPage::ActiveRecordExtension
9 | end
10 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: Ruby
2 |
3 | on: [push,pull_request]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v3
10 | - name: Set up Ruby
11 | uses: ruby/setup-ruby@v1
12 | with:
13 | ruby-version: 3.1.2
14 | bundler-cache: false
15 | - run: bundle install
16 | - name: Run the default task
17 | run: bundle exec rake
18 |
--------------------------------------------------------------------------------
/lib/fast_page/active_record_extension.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "active_record_methods"
4 |
5 | module FastPage
6 | module ActiveRecordExtension
7 | extend ActiveSupport::Concern
8 |
9 | included do
10 | def self.fast_page
11 | extending do
12 | include(FastPage::ActiveRecordMethods)
13 | end.deferred_join_load
14 | end
15 | end
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/bin/console:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | # frozen_string_literal: true
3 |
4 | require "bundler/setup"
5 | require "fast_page"
6 |
7 | # You can add fixtures and/or initialization code here to make experimenting
8 | # with your gem easier. You can also use a different console, if you like.
9 |
10 | # (If you use this, don't forget to add pry to your Gemfile!)
11 | # require "pry"
12 | # Pry.start
13 |
14 | require "irb"
15 | IRB.start(__FILE__)
16 |
--------------------------------------------------------------------------------
/.github/workflows/licensing.yml:
--------------------------------------------------------------------------------
1 | name: Verify dependency licenses
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | types:
9 | - opened
10 | - reopened
11 | - synchronize
12 |
13 | jobs:
14 | licensing:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/checkout@v3
18 | with:
19 | fetch-depth: 0
20 | - name: Set up Ruby
21 | uses: ruby/setup-ruby@v1
22 | with:
23 | ruby-version: 3.1.2
24 | bundler-cache: false
25 | - run: bundle install
26 | - run: gem install license_finder
27 | - run: license_finder
28 |
--------------------------------------------------------------------------------
/.rubocop.yml:
--------------------------------------------------------------------------------
1 | AllCops:
2 | TargetRubyVersion: 2.4
3 |
4 | Metrics/CyclomaticComplexity:
5 | Enabled: false
6 |
7 | Metrics/PerceivedComplexity:
8 | Enabled: false
9 |
10 | Metrics/ClassLength:
11 | Enabled: false
12 |
13 | Style/StringLiterals:
14 | Enabled: true
15 | EnforcedStyle: double_quotes
16 |
17 | Style/StringLiteralsInInterpolation:
18 | Enabled: true
19 | EnforcedStyle: double_quotes
20 |
21 | Layout/LineLength:
22 | Max: 120
23 |
24 | Metrics/MethodLength:
25 | Enabled: false
26 |
27 | Style/Documentation:
28 | Enabled: false
29 |
30 | Metrics/AbcSize:
31 | Enabled: false
32 |
33 | Layout/LineLength:
34 | Enabled: false
35 |
--------------------------------------------------------------------------------
/doc/dependency_decisions.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - - :permit
3 | - MIT
4 | - :who:
5 | :why:
6 | :versions: []
7 | :when: 2022-08-08 23:11:41.376081000 Z
8 | - - :permit
9 | - Apache 2.0
10 | - :who:
11 | :why:
12 | :versions: []
13 | :when: 2022-08-08 23:11:44.981485000 Z
14 | - - :permit
15 | - Simplified BSD
16 | - :who:
17 | :why:
18 | :versions: []
19 | :when: 2022-08-08 23:11:57.738120000 Z
20 | - - :permit
21 | - New BSD
22 | - :who:
23 | :why:
24 | :versions: []
25 | :when: 2022-08-08 23:12:02.144182000 Z
26 | - - :approve
27 | - json
28 | - :who:
29 | :why:
30 | :versions: []
31 | :when: 2022-08-08 23:13:04.483270000 Z
32 | - - :approve
33 | - json
34 | - :who:
35 | :why:
36 | :versions: []
37 | :when: 2022-08-08 23:13:55.801826000 Z
38 |
--------------------------------------------------------------------------------
/test/test_helper.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "minitest/autorun"
4 | require "active_record"
5 | require "active_support"
6 | require "pry"
7 | require_relative "../lib/fast_page"
8 |
9 | ActiveRecord::Base.establish_connection(
10 | adapter: "sqlite3",
11 | database: ":memory:"
12 | )
13 |
14 | ActiveRecord::Schema.define do
15 | self.verbose = false
16 |
17 | create_table :users, force: true do |t|
18 | t.string :login
19 | t.integer :organization_id
20 | t.timestamps
21 | t.index ["login"], unique: true
22 | end
23 |
24 | create_table :organizations, force: true do |t|
25 | t.string :name
26 | t.timestamps
27 | end
28 |
29 | create_table :accounts, id: false, force: true do |t|
30 | t.integer :account_id, primary_key: true
31 | t.string :name
32 | t.timestamps
33 | end
34 | end
35 |
36 | class Organization < ActiveRecord::Base
37 | end
38 |
39 | class Account < ActiveRecord::Base
40 | self.primary_key = :account_id
41 | end
42 |
43 | class User < ActiveRecord::Base
44 | belongs_to :organization
45 | end
46 |
--------------------------------------------------------------------------------
/test/kaminari_test.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "test_helper"
4 |
5 | require "kaminari"
6 |
7 | class KaminariTest < Minitest::Test
8 | def setup
9 | User.delete_all
10 | Organization.delete_all
11 |
12 | org = Organization.create(name: "planetscale")
13 | User.create(login: "mikeissocool", organization: org)
14 | User.create(login: "iheanyi")
15 | User.create(login: "nicknicknick")
16 | User.create(login: "frances")
17 | User.create(login: "phani")
18 | User.create(login: "jason")
19 | User.create(login: "derek")
20 | User.create(login: "dgraham")
21 | User.create(login: "ayrton")
22 | User.create(login: "dbussink")
23 | end
24 |
25 | def test_kaminari_works
26 | og_page = User.page(2).per(1).order(created_at: :desc)
27 | fast_page = User.page(2).per(1).order(created_at: :desc).fast_page
28 |
29 | assert_equal og_page.length, fast_page.length
30 | assert_equal og_page.first.id, fast_page.first.id
31 | assert_equal og_page.current_page, fast_page.current_page
32 | assert_equal og_page.next_page, fast_page.next_page
33 | assert_equal og_page.prev_page, fast_page.prev_page
34 | end
35 |
36 | def test_kaminari_works_without_count
37 | og_page = User.page(2).per(1).order(created_at: :desc).without_count
38 | fast_page = User.page(2).per(1).order(created_at: :desc).without_count.fast_page
39 |
40 | assert_equal og_page.length, fast_page.length
41 | assert_equal og_page.first.id, fast_page.first.id
42 | assert_equal og_page.current_page, fast_page.current_page
43 | assert_equal og_page.next_page, fast_page.next_page
44 | assert_equal og_page.prev_page, fast_page.prev_page
45 | end
46 | end
47 |
--------------------------------------------------------------------------------
/test/pagy_test.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "test_helper"
4 | require "pagy"
5 |
6 | class PagyTest < Minitest::Test
7 | include Pagy::Backend
8 |
9 | # Need to override pagy_get_items to use `fast_page`
10 | def pagy_get_items(collection, pagy)
11 | collection.offset(pagy.offset).limit(pagy.items).fast_page
12 | end
13 |
14 | Pagy::DEFAULT[:items] = 5
15 |
16 | def params
17 | { page: 1, items: 5 }
18 | end
19 |
20 | def setup
21 | User.delete_all
22 | Organization.delete_all
23 |
24 | org = Organization.create(name: "planetscale")
25 | User.create(login: "mikeissocool", organization: org)
26 | User.create(login: "iheanyi")
27 | User.create(login: "nicknicknick")
28 | User.create(login: "frances")
29 | User.create(login: "phani")
30 | User.create(login: "jason")
31 | User.create(login: "derek")
32 | User.create(login: "dgraham")
33 | User.create(login: "ayrton")
34 | User.create(login: "dbussink")
35 | end
36 |
37 | def test_pagy_works
38 | queries = []
39 |
40 | ActiveSupport::Notifications.subscribe("sql.active_record") do |sql|
41 | queries << sql.payload[:sql]
42 | end
43 |
44 | pagy, records = pagy(User.all)
45 |
46 | assert_equal 5, pagy.items
47 | assert_equal 1, pagy.page
48 | assert_equal 2, pagy.next
49 | assert_equal 5, records.size
50 | assert_equal 3, queries.size
51 |
52 | assert_includes queries, 'SELECT COUNT(*) FROM "users"'
53 | assert_includes queries, 'SELECT "users"."id" FROM "users" LIMIT ? OFFSET ?'
54 | assert_includes queries, 'SELECT "users".* FROM "users" WHERE "users"."id" IN (?, ?, ?, ?, ?)'
55 |
56 | ActiveSupport::Notifications.unsubscribe("sql.active_record")
57 | end
58 | end
59 |
--------------------------------------------------------------------------------
/lib/fast_page/active_record_methods.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | module FastPage
4 | module ActiveRecordMethods
5 | def deferred_join_load
6 | # Must have a limit or offset defined
7 | raise ArgumentError, "You must specify a limit or offset to use fast_page" if !limit_value && !offset_value
8 |
9 | # We load 1 additional record to determine if there is a next page.
10 | # This helps us avoid doing a count over all records
11 | @values[:limit] = limit_value + 1 if limit_value
12 | id_scope = dup
13 | id_scope = id_scope.except(:includes) unless references_eager_loaded_tables?
14 |
15 | # Check if ORDER BY contains aliases that might not exist in a pluck query
16 | ids = if order_references_select_aliases?
17 | # Use select approach to preserve SELECT clause aliases, then extract IDs
18 | id_scope.select(primary_key).map { |record| record.send(primary_key) }
19 | else
20 | # Standard pluck approach works fine
21 | id_scope.pluck(primary_key)
22 | end
23 |
24 | if limit_value
25 | @values[:limit] = limit_value - 1
26 | # Record if there is a next page
27 | @_has_next = ids.length > limit_value
28 | ids = ids.first(limit_value)
29 | end
30 |
31 | if ids.empty?
32 | @records = []
33 | @loaded = true
34 | return self
35 | end
36 |
37 | @records = where(primary_key => ids).unscope(:limit).unscope(:offset).load.records
38 | @loaded = true
39 |
40 | self
41 | end
42 |
43 | private
44 |
45 | def order_references_select_aliases?
46 | !select_values.empty? && select_values.any? { |select| select.to_s.match?(/\s+as\s+/i) }
47 | end
48 | end
49 | end
50 |
--------------------------------------------------------------------------------
/fast_page.gemspec:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "lib/fast_page/version"
4 |
5 | Gem::Specification.new do |spec|
6 | spec.name = "fast_page"
7 | spec.version = FastPage::VERSION
8 | spec.authors = ["Mike Coutermarsh"]
9 | spec.email = ["coutermarsh.mike@gmail.com"]
10 |
11 | spec.summary = "Blazing fast pagination for ActiveRecord with deferred joins "
12 | spec.description = 'FastPage applies the MySQL "deferred join" optimization to your ActiveRecord offset/limit queries.'
13 | spec.homepage = "https://github.com/planetscale/fast_page"
14 | spec.license = "Apache-2.0"
15 | spec.required_ruby_version = ">= 2.4.0"
16 |
17 | # spec.metadata["allowed_push_host"] = "TODO: Set to 'https://mygemserver.com'"
18 |
19 | spec.metadata["homepage_uri"] = spec.homepage
20 | spec.metadata["source_code_uri"] = "https://github.com/planetscale/fast_page"
21 | spec.metadata["changelog_uri"] = "https://github.com/planetscale/fast_page"
22 |
23 | # Specify which files should be added to the gem when it is released.
24 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25 | spec.files = Dir.chdir(File.expand_path(__dir__)) do
26 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27 | end
28 | spec.bindir = "exe"
29 | spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30 | spec.require_paths = ["lib"]
31 |
32 | # For more information and examples about making a new gem, checkout our
33 | # guide at: https://bundler.io/guides/creating_gem.html
34 | spec.add_dependency "activerecord"
35 | spec.add_dependency "activesupport"
36 | spec.add_development_dependency "kaminari", "~> 1.2"
37 | spec.add_development_dependency "pagy", "~> 5.10"
38 | spec.add_development_dependency "pry"
39 | spec.add_development_dependency "sqlite3"
40 | end
41 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: .
3 | specs:
4 | fast_page (0.1.5)
5 | activerecord
6 | activesupport
7 |
8 | GEM
9 | remote: https://rubygems.org/
10 | specs:
11 | actionview (6.0.5.1)
12 | activesupport (= 6.0.5.1)
13 | builder (~> 3.1)
14 | erubi (~> 1.4)
15 | rails-dom-testing (~> 2.0)
16 | rails-html-sanitizer (~> 1.1, >= 1.2.0)
17 | activemodel (6.0.5.1)
18 | activesupport (= 6.0.5.1)
19 | activerecord (6.0.5.1)
20 | activemodel (= 6.0.5.1)
21 | activesupport (= 6.0.5.1)
22 | activesupport (6.0.5.1)
23 | concurrent-ruby (~> 1.0, >= 1.0.2)
24 | i18n (>= 0.7, < 2)
25 | minitest (~> 5.1)
26 | tzinfo (~> 1.1)
27 | zeitwerk (~> 2.2, >= 2.2.2)
28 | ast (2.4.2)
29 | builder (3.2.4)
30 | coderay (1.1.3)
31 | concurrent-ruby (1.1.10)
32 | crass (1.0.6)
33 | erubi (1.11.0)
34 | i18n (1.12.0)
35 | concurrent-ruby (~> 1.0)
36 | json (2.6.2)
37 | kaminari (1.2.2)
38 | activesupport (>= 4.1.0)
39 | kaminari-actionview (= 1.2.2)
40 | kaminari-activerecord (= 1.2.2)
41 | kaminari-core (= 1.2.2)
42 | kaminari-actionview (1.2.2)
43 | actionview
44 | kaminari-core (= 1.2.2)
45 | kaminari-activerecord (1.2.2)
46 | activerecord
47 | kaminari-core (= 1.2.2)
48 | kaminari-core (1.2.2)
49 | loofah (2.18.0)
50 | crass (~> 1.0.2)
51 | nokogiri (>= 1.5.9)
52 | method_source (1.0.0)
53 | minitest (5.16.2)
54 | nokogiri (1.13.8-x86_64-darwin)
55 | racc (~> 1.4)
56 | nokogiri (1.13.8-x86_64-linux)
57 | racc (~> 1.4)
58 | pagy (5.10.1)
59 | activesupport
60 | parallel (1.22.1)
61 | parser (3.1.2.1)
62 | ast (~> 2.4.1)
63 | pry (0.13.1)
64 | coderay (~> 1.1)
65 | method_source (~> 1.0)
66 | racc (1.6.0)
67 | rails-dom-testing (2.0.3)
68 | activesupport (>= 4.2.0)
69 | nokogiri (>= 1.6)
70 | rails-html-sanitizer (1.4.3)
71 | loofah (~> 2.3)
72 | rainbow (3.1.1)
73 | rake (13.0.6)
74 | regexp_parser (2.5.0)
75 | rexml (3.2.5)
76 | rubocop (1.33.0)
77 | json (~> 2.3)
78 | parallel (~> 1.10)
79 | parser (>= 3.1.0.0)
80 | rainbow (>= 2.2.2, < 4.0)
81 | regexp_parser (>= 1.8, < 3.0)
82 | rexml (>= 3.2.5, < 4.0)
83 | rubocop-ast (>= 1.19.1, < 2.0)
84 | ruby-progressbar (~> 1.7)
85 | unicode-display_width (>= 1.4.0, < 3.0)
86 | rubocop-ast (1.21.0)
87 | parser (>= 3.1.1.0)
88 | ruby-progressbar (1.11.0)
89 | sqlite3 (1.4.4)
90 | thread_safe (0.3.6)
91 | tzinfo (1.2.10)
92 | thread_safe (~> 0.1)
93 | unicode-display_width (2.2.0)
94 | zeitwerk (2.6.0)
95 |
96 | PLATFORMS
97 | x86_64-darwin-21
98 | x86_64-linux
99 |
100 | DEPENDENCIES
101 | fast_page!
102 | kaminari (~> 1.2)
103 | pagy (~> 5.10)
104 | pry
105 | rake (~> 13.0)
106 | rubocop (~> 1.7)
107 | sqlite3
108 |
109 | BUNDLED WITH
110 | 2.3.18
111 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
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 coutermarsh.mike@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.
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | **`FastPage` applies the MySQL "deferred join" optimization to your ActiveRecord offset/limit queries.⚡️**
4 |
5 | [](https://badge.fury.io/rb/fast_page)
6 |
7 | ## Usage
8 |
9 | Add `fast_page` to your Gemfile.
10 |
11 | ```ruby
12 | gem 'fast_page'
13 | ```
14 |
15 | You can then use the `fast_page` method on any ActiveRecord::Relation that is using offset/limit.
16 |
17 | ### Example
18 | Here is a slow pagination query:
19 | ```ruby
20 | Post.all.order(created_at: :desc).limit(25).offset(100)
21 | # Post Load (1228.7ms) SELECT `posts`.* FROM `posts` ORDER BY `posts`.`created_at` DESC LIMIT 25 OFFSET 100
22 | ```
23 |
24 | Add `.fast_page` to your slow pagination query. It breaks it up into two, much faster queries.
25 | ```ruby
26 | Post.all.order(created_at: :desc).limit(25).offset(100).fast_page
27 | # Post Pluck (456.9ms) SELECT `posts`.`id` FROM `posts` ORDER BY `posts`.`created_at` DESC LIMIT 25 OFFSET 100
28 | # Post Load (0.4ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` IN (1271528, 1271527, 1271526, 1271525, 1271524, 1271523, 1271522, 1271521, 1271520, 1271519, 1271518, 1271517, 1271516, 1271515, 1271514, 1271512, 1271513, 1271511, 1271510, 1271509, 1271508, 1271507, 1271506, 1271505, 1271504) ORDER BY `posts`.`created_at` DESC
29 | ```
30 |
31 | ## Benchmarks
32 | We wanted to see just how much faster using the deferred join could be. We took a table with about ~1 million records in it and benchmarked the standard ActiveRecord offset/limit query vs the query with FastPage.
33 |
34 | Here is the query:
35 | ```ruby
36 | AuditLogEvent.page(num).per(100).where(owner: org).order(created_at: :desc)
37 | ```
38 |
39 | Both `owner` and `created_at` are indexed.
40 |
41 |
42 |
43 | As you can see in the chart above, it's significantly faster the further into the table we paginate.
44 |
45 | ## Compatible pagination libraries
46 | `FastPage` has been tested and works with these existing popular pagination gems. If you try it with any other gems, please let us know!
47 |
48 | ### Kaminari
49 | Add `.fast_page` to the end of your existing [Kaminari](https://github.com/kaminari/kaminari) pagination queries.
50 |
51 | ```ruby
52 | Post.all.page(5).per(25).fast_page
53 | ```
54 |
55 | ### Pagy
56 | In any controller that you want to use `fast_page`, add the following method. This will modify the query [Pagy](https://github.com/ddnexus/pagy) uses when retrieving the records.
57 |
58 | ```ruby
59 | def pagy_get_items(collection, pagy)
60 | collection.offset(pagy.offset).limit(pagy.items).fast_page
61 | end
62 | ```
63 |
64 |
65 | ## How this works
66 |
67 | The most common form of pagination is implemented using LIMIT and OFFSET.
68 |
69 | In this example, each page returns 50 blog posts. For the first page, we grab the first 50 posts. On the 2nd page we grab 100 posts and throw away the first 50. As the `OFFSET` increases, each additional page becomes more expensive for the database to serve.
70 |
71 | ```sql
72 | -- Page 1
73 | SELECT * FROM posts ORDER BY created_at DESC LIMIT 50;
74 | -- Page 2
75 | SELECT * FROM posts ORDER BY created_at DESC LIMIT 50 OFFSET 50;
76 | -- Page 3
77 | SELECT * FROM posts ORDER BY created_at DESC LIMIT 50 OFFSET 100;
78 | ```
79 |
80 | This method of pagination works well until you have a large number of records. The later pages become very expensive to serve. Because of this, applications will often have to limit the maximum number of pages they allow users to view or swap to cursor based pagination.
81 |
82 | ### Deferred join technique
83 |
84 | [High Performance MySQL](https://learning.oreilly.com/library/view/high-performance-mysql/9781492080503/) recommends using a "deferred join" to increase the efficiency of LIMIT/OFFSET pagination for large tables.
85 |
86 | ```sql
87 | SELECT * FROM posts
88 | INNER JOIN(select id from posts ORDER BY created_at DESC LIMIT 50 OFFSET 10000)
89 | AS lim USING(id);
90 | ```
91 |
92 | Notice that we first select the ID of all the rows we want to show, then the data for those rows. This technique works "because it lets the server examine as little data as possible in an index without accessing rows."
93 |
94 | The FastPage gem makes it easy to apply this optimization to any `ActiveRecord::Relation` using offset/limit.
95 |
96 | To learn more on how this works, check out this blog post: [Efficient Pagination Using Deferred Joins](https://aaronfrancis.com/2022/efficient-pagination-using-deferred-joins)
97 |
98 | ## When should I use this?
99 | `fast_page` works best on pagination queries that include an `ORDER BY`. It becomes more effective as the page number increases. You should test it on your application's data to see how it improves your query times.
100 |
101 | We have only tested `fast_page` with MySQL. It likely does not produce the same results for other databases. If you test it, please let us know!
102 |
103 | Because `fast_page` runs 2 queries instead of 1, it is very likely a bit slower for early pages. The benefits begin as the user gets into deeper pages. It's worth testing to see at which page your application gets faster from using `fast_page` and only applying to your queries then.
104 |
105 | ```ruby
106 | posts = Post.all.page(params[:page]).per(25)
107 | # Use fast page after page 5, improves query performance
108 | posts = posts.fast_page if params[:page] > 5
109 | ```
110 |
111 | ## Thank you :heart:
112 | This gem was inspired by [Hammerstone's `fast-paginate` for Laravel](https://github.com/hammerstonedev/fast-paginate) and [@aarondfrancis](https://github.com/aarondfrancis)'s excellent blog post: [Efficient Pagination Using Deferred Joins](https://aaronfrancis.com/2022/efficient-pagination-using-deferred-joins). We were so impressed with the results, we had to bring this to Rails as well.
113 |
114 | ## Contributing
115 |
116 | Bug reports and pull requests are welcome on GitHub at https://github.com/planetscale/fast_page. 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/planetscale/fast_page/blob/main/CODE_OF_CONDUCT.md).
117 |
118 | ## License
119 |
120 | The gem is available as open source under the terms of the [Apache-2.0 license](https://github.com/planetscale/fast_page/blob/main/LICENSE).
121 |
122 | ## Code of Conduct
123 |
124 | Everyone interacting in the FastPage project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/planetscale/fast_page/blob/main/CODE_OF_CONDUCT.md).
125 |
--------------------------------------------------------------------------------
/test/fast_page_test.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "test_helper"
4 |
5 | class FastPageTest < Minitest::Test
6 | def setup
7 | User.delete_all
8 | Organization.delete_all
9 | Account.delete_all
10 |
11 | org = Organization.create(name: "planetscale")
12 | User.create(login: "mikeissocool", organization: org)
13 | User.create(login: "iheanyi")
14 | User.create(login: "nicknicknick")
15 | User.create(login: "frances")
16 | User.create(login: "phani")
17 | User.create(login: "jason")
18 | User.create(login: "derek")
19 | User.create(login: "dgraham")
20 | User.create(login: "ayrton")
21 | User.create(login: "dbussink")
22 |
23 | Account.create(account_id: 1, name: "planetscale")
24 | Account.create(account_id: 2, name: "mikeissocool")
25 | end
26 |
27 | def test_executes_extra_id_query
28 | count = 0
29 | ActiveSupport::Notifications.subscribe("sql.active_record") { count += 1 }
30 |
31 | User.all.limit(5).fast_page
32 |
33 | assert_equal 2, count
34 |
35 | ActiveSupport::Notifications.unsubscribe("sql.active_record")
36 | end
37 |
38 | def test_correct_sql
39 | queries = []
40 |
41 | ActiveSupport::Notifications.subscribe("sql.active_record") do |sql|
42 | queries << sql.payload[:sql]
43 | end
44 |
45 | User.all.limit(5).fast_page
46 |
47 | assert_equal 2, queries.size
48 | assert_includes queries, 'SELECT "users"."id" FROM "users" LIMIT ?'
49 | assert_includes queries, 'SELECT "users".* FROM "users" WHERE "users"."id" IN (?, ?, ?, ?, ?)'
50 |
51 | ActiveSupport::Notifications.unsubscribe("sql.active_record")
52 | end
53 |
54 | def test_correct_for_accounts_sql
55 | queries = []
56 |
57 | ActiveSupport::Notifications.subscribe("sql.active_record") do |sql|
58 | queries << sql.payload[:sql]
59 | end
60 |
61 | Account.all.limit(2).fast_page
62 |
63 | assert_equal 2, queries.size
64 | assert_includes queries, 'SELECT "accounts"."account_id" FROM "accounts" LIMIT ?'
65 | assert_includes queries, 'SELECT "accounts".* FROM "accounts" WHERE "accounts"."account_id" IN (?, ?)'
66 |
67 | ActiveSupport::Notifications.unsubscribe("sql.active_record")
68 | end
69 |
70 | def test_removes_includes_id_query
71 | queries = []
72 |
73 | ActiveSupport::Notifications.subscribe("sql.active_record") do |sql|
74 | queries << sql.payload[:sql]
75 | end
76 |
77 | User.all.includes(:organization).limit(50).fast_page
78 |
79 | assert_equal 3, queries.size
80 |
81 | # Organizations are not included on the ID query (not needed)
82 | assert_includes queries, 'SELECT "users"."id" FROM "users" LIMIT ?'
83 | assert_includes queries, 'SELECT "users".* FROM "users" WHERE "users"."id" IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
84 | # Includes are still loaded
85 | assert_includes queries, 'SELECT "organizations".* FROM "organizations" WHERE "organizations"."id" = ?'
86 |
87 | ActiveSupport::Notifications.unsubscribe("sql.active_record")
88 | end
89 |
90 | def test_returns_same_results
91 | og = User.all.limit(5).offset(5).order(created_at: :desc)
92 | fast = User.all.limit(5).offset(5).order(created_at: :desc).fast_page
93 |
94 | assert_equal og.length, fast.length
95 | assert_equal og.select(&:id), fast.select(&:id)
96 | end
97 |
98 | def test_errors_without_limit_or_offset
99 | assert_raises(ArgumentError) do
100 | User.all.fast_page
101 | end
102 | end
103 |
104 | def test_works_limit_only
105 | og = User.all.limit(5).order(created_at: :desc)
106 | fast = User.all.limit(5).order(created_at: :desc).fast_page
107 |
108 | assert_equal og.length, fast.length
109 | assert_equal og.select(&:id), fast.select(&:id)
110 | end
111 |
112 | def test_works_offset_only
113 | og = User.all.offset(5).order(created_at: :desc)
114 | fast = User.all.offset(5).order(created_at: :desc).fast_page
115 |
116 | assert_equal og, fast
117 | end
118 |
119 | def test_to_a_returns_an_array
120 | assert_equal Array, User.all.limit(5).fast_page.to_a.class
121 | end
122 |
123 | def test_subquery_alias_ordering_fixed
124 | # This test verifies the fix for GitHub issue #12
125 | # where ordering by a subquery alias used to fail with fast_page
126 | #
127 | # Create a query that uses a subquery with an alias in ORDER BY
128 | # This simulates: SELECT users.*, (SELECT COUNT(*) FROM organizations WHERE organizations.id = users.organization_id) AS org_count FROM users ORDER BY org_count
129 | relation = User.select("users.*, (SELECT COUNT(*) FROM organizations WHERE organizations.id = users.organization_id) AS org_count")
130 | .order("org_count ASC")
131 | .limit(5)
132 |
133 | # The original query should work fine
134 | original_result = relation.to_a
135 |
136 | # Now fast_page should also work without errors
137 | fast_page_result = relation.fast_page.to_a
138 |
139 | # Both queries should return the same results
140 | assert_equal original_result.length, fast_page_result.length
141 | assert_equal original_result.map(&:id), fast_page_result.map(&:id)
142 |
143 | # Verify that the subquery alias is preserved in the results
144 | original_result.each_with_index do |record, index|
145 | assert_equal record.org_count, fast_page_result[index].org_count
146 | end
147 | end
148 |
149 | def test_alias_detection_logic
150 | # Test that alias detection works correctly for different scenarios
151 |
152 | # Regular column ordering should not trigger alias detection
153 | regular_relation = User.order("login ASC").limit(5)
154 | fast_page_regular = regular_relation.fast_page
155 | refute fast_page_regular.send(:order_references_select_aliases?), "Regular column ordering should not be detected as alias"
156 |
157 | # Alias ordering should trigger alias detection
158 | alias_relation = User.select("users.*, (SELECT COUNT(*) FROM organizations WHERE organizations.id = users.organization_id) AS org_count")
159 | .order("org_count ASC")
160 | .limit(5)
161 | fast_page_alias = alias_relation.fast_page
162 | assert fast_page_alias.send(:order_references_select_aliases?), "Alias ordering should be detected"
163 |
164 | # Mixed ordering (real column + alias) should trigger alias detection
165 | mixed_relation = User.select("users.*, (SELECT COUNT(*) FROM organizations WHERE organizations.id = users.organization_id) AS org_count")
166 | .order("login ASC, org_count DESC")
167 | .limit(5)
168 | fast_page_mixed = mixed_relation.fast_page
169 | assert fast_page_mixed.send(:order_references_select_aliases?), "Mixed ordering with aliases should be detected"
170 | end
171 | end
172 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------