rails icon indicating copy to clipboard operation
rails copied to clipboard

Support IN queries on array columns

Open gregnavis opened this issue 2 months ago • 3 comments

Motivation / Background

A non-array column can be queried via where(name: [value1, value2]) which is automatically converted to name IN (value1, value2) in SQL. An array column would treat that array as the value to search for, so it'd be natural to expect an array of arrays would result in an IN query. Unfortunately, that wasn't the case as where(name: [[value1], [value2]]) would return name = {{value1}, {value2}} in SQL, instead of name IN ({value1}, {value2}).

Detail

That behavior stemmed from the fact that Active Record would force equality comparison for array columns if the value was an array. In order to allow IN queries this check was change to check whether it's a one-dimensional array by checking that the first item of is not an array.

After these changes the following logic applies for querying array columns:

  1. Using a one-dimensional array results in an ordinary equality query.
  2. Using a two-dimensional array produces an IN query.

Checklist

Before submitting the PR make sure the following are checked:

  • [x] This Pull Request is related to one change. Changes that are unrelated should be opened in separate PRs.
  • [x] Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • [x] Tests are added or updated if you fix a bug or add a feature.
  • [x] CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.

gregnavis avatar Feb 20 '24 12:02 gregnavis