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.



263
264
265
266
# File 'lib/pgtk/pool.rb', line 263

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



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/pgtk/pool.rb', line 273

def exec(query, args = [], result = 0)
  start = Time.now
  sql = query.is_a?(Array) ? query.join(' ') : query
  @conn.instance_variable_set(:@pgtk_last_query, sql)
  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} >> #{start.ago} / #{@conn.object_id}")
  else
    @log.info("#{sql} >> #{start.ago}")
  end
  out
end