Class: Pgtk::Pool::Txn

Inherits:
Object
  • Object
show all
Defined in:
lib/pgtk/pool.rb

Overview

A temporary class to execute a single SQL request.

Instance Method Summary collapse

Constructor Details

#initialize(conn, log) ⇒ Txn

Returns a new instance of Txn.



168
169
170
171
# File 'lib/pgtk/pool.rb', line 168

def initialize(conn, log)
  @conn = conn
  @log = log
end

Instance Method Details

#exec(query, args = [], result = 0) {|Hash| ... } ⇒ Object

Exec a single parameterized command.

Parameters:

  • query (String)

    The SQL query with params inside (possibly)

  • args (Array) (defaults to: [])

    List of arguments

  • result (Integer) (defaults to: 0)

    Should be 0 for text results, 1 for binary

Yields:

  • (Hash)

    Rows



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/pgtk/pool.rb', line 178

def exec(query, args = [], result = 0)
  start = Time.now
  sql = query.is_a?(Array) ? query.join(' ') : query
  begin
    out =
      if args.empty?
        @conn.exec(sql) do |res|
          if block_given?
            yield res
          else
            res.each.to_a
          end
        end
      else
        @conn.exec_params(sql, args, result) do |res|
          if block_given?
            yield res
          else
            res.each.to_a
          end
        end
      end
  rescue StandardError => e
    @log.error("#{sql}: #{e.message}")
    raise e
  end
  lag = Time.now - start
  if lag < 1
    @log.debug("#{sql}: #{(lag * 1000).round}ms / #{@conn.object_id}")
  else
    @log.info("#{sql}: #{format('%.02f', lag)}s")
  end
  out
end