Class: ActiveRecord::PostgreSQLCursor
- Inherits:
-
Object
- Object
- ActiveRecord::PostgreSQLCursor
- Includes:
- Enumerable
- Defined in:
- lib/activerecord-postgresql-cursors.rb
Overview
PostgreSQLCursor is an Enumerable class so you can use each, map, any? and all of those nice Enumerable methods.
At the moment, cursors aren’t scrollable and are fetch forward-only and read-only.
Instance Method Summary collapse
-
#each ⇒ Object
Calls block once for each record in the cursor, passing that record as a parameter.
-
#initialize(model, cursor_name, relation, join_dependency = nil) ⇒ PostgreSQLCursor
constructor
A new instance of PostgreSQLCursor.
- #inspect ⇒ Object
Constructor Details
#initialize(model, cursor_name, relation, join_dependency = nil) ⇒ PostgreSQLCursor
Returns a new instance of PostgreSQLCursor.
15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/activerecord-postgresql-cursors.rb', line 15 def initialize(model, cursor_name, relation, join_dependency = nil) @model = model @relation = relation @join_dependency = join_dependency @cursor_name = if cursor_name @model.connection.quote_table_name(cursor_name.gsub(/"/, '\"')) end @query = model.connection.unprepared_statement do relation.to_sql end end |
Instance Method Details
#each ⇒ Object
Calls block once for each record in the cursor, passing that record as a parameter.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/activerecord-postgresql-cursors.rb', line 35 def each @model.transaction do begin declare_cursor if @join_dependency rows = Array.new last_id = nil while row = fetch_forward instantiated_row = @join_dependency.instantiate([row], @join_dependency.aliases).first current_id = instantiated_row[@join_dependency.join_root.primary_key] last_id ||= current_id if last_id == current_id rows << row last_id = current_id else yield @join_dependency.instantiate(rows, @join_dependency.aliases).first rows = [ row ] end last_id = current_id end if !rows.empty? yield @join_dependency.instantiate(rows, @join_dependency.aliases).first end else while row = fetch_forward yield @model.instantiate(row) end end ensure close_cursor end end nil end |
#inspect ⇒ Object
29 30 31 |
# File 'lib/activerecord-postgresql-cursors.rb', line 29 def inspect %{#<ActiveRecord::PostgreSQLCursor cursor_name: "#{cursor_name}", query: "#{@query}">} end |