Class: Cursor
- Inherits:
-
Object
- Object
- Cursor
- Defined in:
- lib/has_helpers/cursor.rb
Overview
Encapsulates cursor database functionality. Currently only works with PostgreSQL.
Class Method Summary collapse
-
.execute(**cursor_args, &block) ⇒ Object
Example Cursor.execute(sql: "SELECT * FROM users") do |cursor| while user = cursor.next() do ...
Instance Method Summary collapse
- #close! ⇒ Object
- #declare! ⇒ Object
-
#initialize(name: random_name, connection: ActiveRecord::Base.connection, sql:) ⇒ Cursor
constructor
A new instance of Cursor.
-
#next(n = 1) ⇒ Object
Fetches the next
nrecords from the cursor.
Constructor Details
#initialize(name: random_name, connection: ActiveRecord::Base.connection, sql:) ⇒ Cursor
Returns a new instance of Cursor.
20 21 22 23 24 |
# File 'lib/has_helpers/cursor.rb', line 20 def initialize(name: random_name, connection: ActiveRecord::Base.connection, sql:) @name = name @connection = connection @sql = sql end |
Class Method Details
.execute(**cursor_args, &block) ⇒ Object
Example
Cursor.execute(sql: "SELECT * FROM users") do |cursor| while user = cursor.next() do ... end end
12 13 14 15 16 17 18 |
# File 'lib/has_helpers/cursor.rb', line 12 def self.execute(**cursor_args, &block) cursor = Cursor.new(**cursor_args) cursor.declare! block.call(cursor) ensure cursor.close! end |
Instance Method Details
#close! ⇒ Object
30 31 32 |
# File 'lib/has_helpers/cursor.rb', line 30 def close! @connection.execute "CLOSE #{@name};" end |
#declare! ⇒ Object
26 27 28 |
# File 'lib/has_helpers/cursor.rb', line 26 def declare! @connection.execute "DECLARE #{@name} CURSOR WITH HOLD FOR #{@sql};" end |
#next(n = 1) ⇒ Object
Fetches the next n records from the cursor. Returns nil if there
are no records left.
36 37 38 39 |
# File 'lib/has_helpers/cursor.rb', line 36 def next(n = 1) result = @connection.execute("FETCH #{n} FROM #{@name};") n == 1 ? result.first : result.to_a.presence end |