Class: ActiveRecord::PostgreSQLCursor

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(model, cursor_name, relation, join_dependency = nil) ⇒ PostgreSQLCursor

Returns a new instance of PostgreSQLCursor.



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/activerecord-postgresql-cursors.rb', line 16

def initialize(model, cursor_name, relation, join_dependency = nil)
  @model = model
  @relation = relation
  @join_dependency = join_dependency

  @cursor_name = (@model.connection.quote_table_name(cursor_name.gsub('"', '\"')) if cursor_name)

  @query = model.connection.unprepared_statement do
    relation.to_sql
  end
end

Instance Method Details

#eachObject

Calls block once for each record in the cursor, passing that record as a parameter.



34
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
72
73
74
75
# File 'lib/activerecord-postgresql-cursors.rb', line 34

def each
  @model.transaction do
    declare_cursor

    if @join_dependency
      rows = []
      last_id = nil

      until (row = fetch_forward).empty?
        instantiated_row = @join_dependency.instantiate(row, true).first
        current_id = instantiated_row[@join_dependency.send(:join_root).primary_key]
        last_id ||= current_id

        if last_id == current_id
          rows << row.first.values
          last_id = current_id
        else
          result_set = ActiveRecord::Result.new(row.columns, rows, row.column_types)

          yield @join_dependency.instantiate(result_set, true).first

          rows = [row.first.values]
        end

        last_id = current_id
      end

      unless rows.empty?
        result_set = ActiveRecord::Result.new(row.columns, rows, row.column_types)

        yield @join_dependency.instantiate(result_set, true).first
      end
    else
      until (row = fetch_forward).empty?
        yield @model.instantiate(row.first)
      end
    end
  ensure
    close_cursor
  end
  nil
end

#inspectObject



28
29
30
# File 'lib/activerecord-postgresql-cursors.rb', line 28

def inspect
  %{#<ActiveRecord::PostgreSQLCursor cursor_name: "#{cursor_name}", query: "#{@query}">}
end