Skip to content

ruflet_record: apply a relation's limit, offset, distinct and order in writes, count, last and find_each; chain scopes on relations - #118

Open
AdamMusa wants to merge 3 commits into
mainfrom
audit/record-relation-scope
Open

AdamMusa wants to merge 3 commits into
mainfrom
audit/record-relation-scope

Conversation

@AdamMusa

@AdamMusa AdamMusa commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Fixes #117

Problem

Several RufletRecord::Relation methods ignored the relation's own limit, offset, distinct or order:

  • update_all and delete_all dropped the limit and offset. Item.order(:id).limit(1).delete_all deleted every row, and so did offset(9).delete_all and limit(0).delete_all.
  • count put COUNT(*) in the outer query, beside LIMIT, OFFSET and DISTINCT. limit(2).count returned 10, offset(8).count returned nil, and select(:active).distinct.count returned 10.
  • last always reordered by primary key descending. order(qty: :desc).last returned the row with the highest qty, and limit(3).last returned the last row of the whole table.
  • find_each replaced the relation's limit with the batch size, so limit(3).find_each visited every row.
  • Scopes did not chain. Item.named.big and Item.where(...).named raised NoMethodError, although the README lists model scopes among the methods that build relations.

What changed

Only packages/ruflet_record: relation.rb, base.rb, the README, test/mruby_smoke.rb, and the new test/relation_scope_test.rb.

Call Before After
update_all / delete_all with a limit or offset ... WHERE (<where>): every matching row ... WHERE ("t"."id" IN (SELECT [DISTINCT] "t"."id" FROM "t" ... ORDER BY ... LIMIT ? OFFSET ?)). DISTINCT is kept from a distinct relation, so a distinct join changes each selected row once
count with a limit, offset or distinct SELECT [DISTINCT] COUNT(*) AS value FROM "t" ... LIMIT ? SELECT COUNT(*) AS value FROM (SELECT 1 FROM "t" ... LIMIT ?) AS "subquery"; count(:col) counts the non-NULL values of col; a distinct relation with one selected column counts its distinct values, NULL excluded
last with an order reordered by primary key descending the relation's order reversed. An order given as RufletRecord.sql(...) cannot be reversed safely, so it is counted and read with OFFSET instead (two queries)
last with a limit or offset ignored them loads the selected rows and returns the last of them, as Active Record does
find_each with a limit visited every row stops after the limit
relation.some_scope(...) NoMethodError the scope's relation is merged in: its conditions and order are added, and its select, limit and offset replace the relation's. A scope that calls reorder replaces the order, as in Active Record

A blank order entry, such as order(params[:sort]) with no sort given (nil, "", {}), adds nothing to ORDER BY. last, and count and the writes with a limit or offset, skip it, as Active Record does. order(nil).last sends the same SQL as before.

How scopes chain:

  • Relation#method_missing delegates only names declared with scope, including those a parent model declares. A parent's scope over the same table applies to the subclass's relation.
  • Other class methods are not delegated. RufletRecord has no Active Record scoping, so def self.total; sum(:qty); end called on a relation would ignore that relation's conditions and return a silently wrong result. It keeps raising NoMethodError.
  • A scope named after a private method every object has, such as open or format (Kernel), keeps raising NoMethodError on a relation, as on main. mruby raises before method_missing runs, so CRuby raises too and development matches the device. Item.open.where(...) works. The README says to start the chain with such a scope or rename it.
  • A scope that returns another model's relation raises ArgumentError through merge.
  • merge itself is unchanged: it still adds the other relation's order, even one built with reorder.
  • method_missing is public, as Base#method_missing already is. mruby does not dispatch to a private method_missing for a call with a receiver.

The rules hold for every call outside those rows:

  • The same SQL. Relations without a limit, offset or distinct send byte-identical SQL and binds for count, count(:col), update_all, delete_all, last, first and find_each.
  • The same results. sum, average, minimum and maximum with a limit or offset are unchanged, as is find_each applying an offset to each batch. Active Record 8.1 gives the same results for these. first without an order is also unchanged: it sends LIMIT 1 without ORDER BY, while Active Record orders by the primary key. That difference is left for a separate decision.

Behavior changes

Each one is a bug fix. Each changes a result only where today's result is wrong, and the first one loses data.

  1. update_all and delete_all with a limit or offset change only the rows the relation selects. Before, they changed every row the where clauses matched. That includes limit(0), which now changes nothing.
    • On a distinct relation with a join, each selected row changes once. Active Record 8.1 raises for delete_all there and ignores distinct in update_all (deprecated), so this case differs from AR on purpose.
  2. count with a limit, offset or distinct counts the selected rows. Before, it returned the unlimited count, or nil with an offset past the first row.
    • On a distinct relation with one selected column, count counts that column's distinct non-NULL values, as Active Record does.
    • With several selected columns, it counts the distinct rows. Active Record 8.1 returns a value there that depends on its aliasing, so this one case differs from AR on purpose.
    • distinct.count with a join now counts each record once, matching AR's COUNT(DISTINCT id).
  3. last follows the relation's order and its limit or offset. Before, it returned the row with the highest primary key. last without an order, limit or offset is unchanged, and so is last whose only order entries are blank.
  4. find_each on a relation with a limit stops after that limit.
  5. Scopes chain on relations and association readers. This is additive: these calls raised NoMethodError before.

How verified

All on the head, which includes main at a668af6 (merge commit 085ff97).

  • New regression test. test/relation_scope_test.rb has 29 tests. Expected values come from Active Record 8.1.4.1 on SQLite for the same calls, except the cases this body says differ. Four tests pin the SQL and binds of relations without a limit, offset or distinct, byte for byte; one of them also pins order(nil).last.
  • Bug planted back. Against main's lib, the new test file gives 17 failures and 6 errors. Against the previous head of this PR (3c7654d) it fails 5 tests: the four added in this round (blank order entries, writes on a distinct join, a scope that reorders, a Kernel-named scope) and the order(nil).last SQL check. Each of 10 mutations of the new code (each blank-order skip, the DISTINCT in writes, the * guard in count, the reorder flag, the private-name guard, and making merge honor reorder) fails at least one test.
  • Full ruflet_record suite. Each of the 15 test files ran in its own process with -w, with no warnings, on CRuby 4.0.5 and on 3.4.5 (the CI version): 124 runs, 707 assertions, 0 failures. rake test gives the same. The new file passes with seeds 1, 7, 42, 999, 31337, 2024 and 55555.
  • SQL corpus. A script logs every statement for 38 calls without a limit, offset or distinct, among them count, count(:col), sum and maximum with a limit, update_all, delete_all, destroy, update_columns, save, last, first, find_each, a scope, pluck, exists?, pick and distinct.pluck. Its output on main and on this branch is identical.
  • Active Record comparison. 60 adversarial cases, the 31 from the first round, and 39 more (blank orders, distinct joins with writes, aggregates with an offset, scopes that reorder) ran on AR 8.1.4.1 and on this branch. They match except the differences listed above: writes on a distinct join, select(:a, :b).distinct.count, merge with reorder, a Kernel-named scope on a relation, limit(2).count(RufletRecord.sql("*")) (2 here, AR raises), and limit(3).first(5) (5 here and on main, 3 in AR).
  • Embedded mruby VM. On host_vm mruby with this branch's lib loaded over the preloaded copy, the 60 and the 39 cases give the same results as CRuby, apart from the wording of one NoMethodError message, and test/mruby_smoke.rb passes. With main's lib it fails at the new scope-chaining check. Both changed files compile with the VM's mrbc.
  • test/mruby_smoke.rb gains checks for scope chaining, count with a limit, last with an order, a blank order, and delete_all with a limit. It runs against the copy preloaded in the VM, so in the VM it passes only after the VM is rebuilt from this source. PR ruflet_record: open-ended ranges in where (18.., ..17, ...18) no longer match nothing #107 handled its new smoke checks the same way.
  • H1 goldens. cd packages/ruflet && ruby test/compat/compat.rb --jobs 4 checked 358 goldens with no difference. ruby -Ilib -Itest test/compat_goldens_test.rb: 366 runs, 0 failures.

Rollout and follow-ups

  • The committed prebuilt VM libraries still hold the old ruflet_record, and rebuilding the runtime is on hold. Until the VM is rebuilt, self-contained device apps keep the old behavior, including order(:id).limit(1).delete_all deleting every row, while CRuby ruflet run and server mode get the fix. The owner's local host_vm build already fails test/mruby_smoke.rb at the endless-range check, before the new checks. That predates this PR.
  • ruflet.dev (app/content/docs/ruflet_record.md) says last orders by the primary key whatever the relation's order, and that User.order(:name).active does not work. Once this ships, that page needs an update marked for the next release.
  • Not changed here: order(nil).to_a and order(nil).first raise StatementInvalid on main and still do, and limit(3).first(5) returns 5 records.

…verywhere; chain scopes on relations

update_all and delete_all with a limit or offset now change only the rows
the relation selects (pk IN subquery), instead of every row its where
clauses match. count with a limit, offset or distinct counts from a
subquery. last follows the relation's order and, with a limit or offset,
returns the last selected row. find_each stops after the relation's limit.
A model's scopes chain on its relations.

Relations without a limit, offset or distinct send the same SQL as before.
sum, average, minimum, maximum, first and find_each's offset are unchanged,
as in Active Record.

Fixes #117
…keep distinct in writes; scopes that reorder

A blank order entry (order(nil), order(""), reorder(nil)) left a bare
ORDER BY in the queries that now keep the relation's order, so last, and
count and update_all/delete_all with a limit, raised StatementInvalid.
They skip such entries, as Active Record does; order(nil).last sends the
same SQL as before.

The primary-key subquery of a write keeps DISTINCT, so a distinct join
with a limit changes each selected row once.

A scope that calls reorder replaces the relation's order when it chains,
as in Active Record. merge is unchanged.

A scope named after a private method (Kernel#open, #format) raises
NoMethodError on a relation under CRuby too, as it does on mruby.

README: aggregates ignore the limit but not the offset; scope reorder and
Kernel-named scopes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant