我有一个包含多个现有表的旧数据库,我想查询一个没有主键的旧表中的数千条记录
LegacyTable.where(condition, start_date, end_date).find_each do |record|
yield record
end
但它会抛出以下错误:
ORA-01741: illegal zero-length identifier
因为它自动生成 按“LegacyTable”排序。""
根据api
NOTE: It's not possible to set the order. That is automatically set to ascending on the primary key (“id ASC”) to make the batch ordering work. This also means that this method only works with integer-based primary keys.
然后我在模型中设置了 self.primary_key = 'TRANSACTION_ID'
,但是 TRANSACTION_ID 只是旧表中的一个索引。然后它抛出另一个异常:
RuntimeError (Primary key not included in the custom select clause):
如何在rails中进行批量查询?如果使用 Java,我可以只添加 fetchSize 参数,而不需要表中的主键。
最佳答案
ActiveRecord 的 find_in_batches
(find_each
基于)依赖主键排序在多个查询中执行批量提取 (details)。正如 @aliibrahim 已经提到的,您必须自己实现分页。
虽然我知道问题是关于 Oracle 的,但对于来自 Google 的其他人来说,值得一提的是,对于使用 PostgreSQL 的人来说,有一个很好的解决问题的方法:postgresql_cursor gem 。
PostgreSQL Cursor is an extension to the ActiveRecord PostgreSQLAdapter for very large result sets. It provides a cursor open/fetch/close interface to access data without loading all rows into memory, and instead loads the result rows in "chunks" (default of 1_000 rows), buffers them, and returns the rows one at a time.
关于ruby-on-rails - Rails - 批处理 sql 查询 - 自定义选择子句中不包含主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500879/