Repository navigation
Conversation
…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.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #117
Problem
Several
RufletRecord::Relationmethods ignored the relation's own limit, offset, distinct or order:update_allanddelete_alldropped the limit and offset.Item.order(:id).limit(1).delete_alldeleted every row, and so didoffset(9).delete_allandlimit(0).delete_all.countputCOUNT(*)in the outer query, besideLIMIT,OFFSETandDISTINCT.limit(2).countreturned 10,offset(8).countreturnednil, andselect(:active).distinct.countreturned 10.lastalways reordered by primary key descending.order(qty: :desc).lastreturned the row with the highestqty, andlimit(3).lastreturned the last row of the whole table.find_eachreplaced the relation's limit with the batch size, solimit(3).find_eachvisited every row.Item.named.bigandItem.where(...).namedraisedNoMethodError, 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 newtest/relation_scope_test.rb.update_all/delete_allwith a limit or offset... WHERE (<where>): every matching row... WHERE ("t"."id" IN (SELECT [DISTINCT] "t"."id" FROM "t" ... ORDER BY ... LIMIT ? OFFSET ?)).DISTINCTis kept from a distinct relation, so a distinct join changes each selected row oncecountwith a limit, offset or distinctSELECT [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 ofcol; a distinct relation with one selected column counts its distinct values, NULL excludedlastwith an orderRufletRecord.sql(...)cannot be reversed safely, so it is counted and read withOFFSETinstead (two queries)lastwith a limit or offsetfind_eachwith a limitrelation.some_scope(...)NoMethodErrorreorderreplaces the order, as in Active RecordA blank order entry, such as
order(params[:sort])with no sort given (nil,"",{}), adds nothing toORDER BY.last, andcountand the writes with a limit or offset, skip it, as Active Record does.order(nil).lastsends the same SQL as before.How scopes chain:
Relation#method_missingdelegates only names declared withscope, including those a parent model declares. A parent's scope over the same table applies to the subclass's relation.scoping, sodef self.total; sum(:qty); endcalled on a relation would ignore that relation's conditions and return a silently wrong result. It keeps raisingNoMethodError.openorformat(Kernel), keeps raisingNoMethodErroron a relation, as onmain. mruby raises beforemethod_missingruns, 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.ArgumentErrorthroughmerge.mergeitself is unchanged: it still adds the other relation's order, even one built withreorder.method_missingis public, asBase#method_missingalready is. mruby does not dispatch to a privatemethod_missingfor a call with a receiver.The rules hold for every call outside those rows:
count,count(:col),update_all,delete_all,last,firstandfind_each.sum,average,minimumandmaximumwith a limit or offset are unchanged, as isfind_eachapplying an offset to each batch. Active Record 8.1 gives the same results for these.firstwithout an order is also unchanged: it sendsLIMIT 1withoutORDER 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.
update_allanddelete_allwith a limit or offset change only the rows the relation selects. Before, they changed every row the where clauses matched. That includeslimit(0), which now changes nothing.delete_allthere and ignoresdistinctinupdate_all(deprecated), so this case differs from AR on purpose.countwith a limit, offset or distinct counts the selected rows. Before, it returned the unlimited count, ornilwith an offset past the first row.countcounts that column's distinct non-NULL values, as Active Record does.distinct.countwith a join now counts each record once, matching AR'sCOUNT(DISTINCT id).lastfollows the relation's order and its limit or offset. Before, it returned the row with the highest primary key.lastwithout an order, limit or offset is unchanged, and so islastwhose only order entries are blank.find_eachon a relation with a limit stops after that limit.NoMethodErrorbefore.How verified
All on the head, which includes
mainat a668af6 (merge commit 085ff97).test/relation_scope_test.rbhas 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 pinsorder(nil).last.main'slib, 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 theorder(nil).lastSQL check. Each of 10 mutations of the new code (each blank-order skip, theDISTINCTin writes, the*guard incount, the reorder flag, the private-name guard, and makingmergehonorreorder) fails at least one test.ruflet_recordsuite. 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 testgives the same. The new file passes with seeds 1, 7, 42, 999, 31337, 2024 and 55555.count,count(:col),sumandmaximumwith a limit,update_all,delete_all,destroy,update_columns,save,last,first,find_each, a scope,pluck,exists?,pickanddistinct.pluck. Its output onmainand on this branch is identical.select(:a, :b).distinct.count,mergewithreorder, a Kernel-named scope on a relation,limit(2).count(RufletRecord.sql("*"))(2 here, AR raises), andlimit(3).first(5)(5 here and onmain, 3 in AR).host_vmmruby with this branch'slibloaded over the preloaded copy, the 60 and the 39 cases give the same results as CRuby, apart from the wording of oneNoMethodErrormessage, andtest/mruby_smoke.rbpasses. Withmain'slibit fails at the new scope-chaining check. Both changed files compile with the VM'smrbc.test/mruby_smoke.rbgains checks for scope chaining,countwith a limit,lastwith an order, a blank order, anddelete_allwith 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.cd packages/ruflet && ruby test/compat/compat.rb --jobs 4checked 358 goldens with no difference.ruby -Ilib -Itest test/compat_goldens_test.rb: 366 runs, 0 failures.Rollout and follow-ups
ruflet_record, and rebuilding the runtime is on hold. Until the VM is rebuilt, self-contained device apps keep the old behavior, includingorder(:id).limit(1).delete_alldeleting every row, while CRubyruflet runand server mode get the fix. The owner's localhost_vmbuild already failstest/mruby_smoke.rbat the endless-range check, before the new checks. That predates this PR.app/content/docs/ruflet_record.md) sayslastorders by the primary key whatever the relation's order, and thatUser.order(:name).activedoes not work. Once this ships, that page needs an update marked for the next release.order(nil).to_aandorder(nil).firstraiseStatementInvalidonmainand still do, andlimit(3).first(5)returns 5 records.