Class: PgConduit::QueryStream

Inherits:
Object
  • Object
show all
Defined in:
lib/pg_conduit/query_stream.rb

Overview

Execute a SQL query and provide the results as a stream

Examples:

Print username and email for all users


conn    = PG::Connection.open
stream  = PgConduit::QueryStream.new(conn)

stream.query('SELECT * FROM users').each_row do |row|
  puts "#{row['username']}, #{row['email']}"
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pool) ⇒ QueryStream

Returns a new instance of QueryStream.

Parameters:

  • pool (ConnectionPool)

    A pool of PG::Connections



16
17
18
# File 'lib/pg_conduit/query_stream.rb', line 16

def initialize(pool)
  @pool = pool
end

Instance Attribute Details

#sqlObject (readonly)

Returns the value of attribute sql.



13
14
15
# File 'lib/pg_conduit/query_stream.rb', line 13

def sql
  @sql
end

Instance Method Details

#each_row {|Hash| ... } ⇒ Object

Execute query and yield each row

Yields:

  • (Hash)

    A hash representing a single row from the result set



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/pg_conduit/query_stream.rb', line 28

def each_row
  @pool.with do |conn|
    conn.send_query @sql
    conn.set_single_row_mode
    loop do
      res = conn.get_result
      break unless res
      res.check
      res.stream_each { |row| yield row }
    end
  end
end

#query(sql) ⇒ self

Parameters:

  • sql (String)

    The SQL query to execute

Returns:

  • (self)


22
23
24
# File 'lib/pg_conduit/query_stream.rb', line 22

def query(sql)
  self.tap { @sql = sql }
end