Repository is archived
No commit activity in last 3 years
No release in over 3 years
Enforces the presence of specific columns in SELECT queries. Useful when you have performance restrictions when specific columns are not included in your WHERE clauses. Indexed columns and partition keys are common examples of such columns.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.15
~> 10.0
~> 3.0
= 0.49.1

Runtime

 Project Readme

RequiredQueryAttributes CircleCI

Enforce presence of specific columns in ActiveRecord queries.

Description

If you have a records table like this:

create_table 'records' do |t|
  t.date     'date'
  t.string   'text'
end

You might want to make sure that SELECT queries always provide a predicate condition on date.

It could be because you have a very large table, and your only good index is on date.

Or maybe your data is partitioned by date, and thus not providing it will trigger full table scan.

RequiredQueryAttributes ensures all SELECT queries provide at least one predicate condition on the desired columns, or they will fail with an exception:

RequiredQueryAttributes::RequiredAttributeMissing:
  Required attributes ["date"] missing from query:
    SELECT "records".* FROM "records" WHERE "records"."text" = 'string_to_find'

Installation

Add this line to your application's Gemfile and execute bundle:

gem 'required_query_attributes'

Usage

Using the same records example:

create_table 'records' do |t|
  t.date     'date'
  t.string   'text'
end

Configure your class:

class Record < ActiveRecord::Base
  include RequiredQueryAttributes
 
  require_query_attribute :date
 
  # Add additional attributes if desired
  # require_query_attribute :text
end

Profit.

FYI

This gem tries to do its job as cleanly as possible, only changing ActiveRecord behaviour when necessary.

There are no global changes to ActiveRecord: only models which you choose to install RequiredQueryAttributes are affected.