Sha256: bc3eaad7760e44e97ed9c1099be385a20f01b41eedcdb7fb235f7dc70bdadc2f

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 KB

Contents

module PgConduit
  # Execute a SQL query and provide the results as a stream
  # @example 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
  #
  class QueryStream
    attr_reader :sql

    # @param pool [ConnectionPool] A pool of PG::Connections
    def initialize(pool)
      @pool = pool
    end

    # @param sql [String] The SQL query to execute
    # @return [self]
    def query(sql)
      self.tap { @sql = sql }
    end

    # Execute query and yield each row
    # @yield [Hash] A hash representing a single row from the result set
    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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pg_conduit-0.1.0 lib/pg_conduit/query_stream.rb