Class: Pgtk::Pool::Txn

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

Overview

A temporary class to execute a single SQL request.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2019-2026 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(conn, log) ⇒ Txn

Returns a new instance of Txn.



17
18
19
20
# File 'lib/pgtk/pool/txn.rb', line 17

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



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/pgtk/pool/txn.rb', line 27

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)
  @conn.instance_variable_set(:@pgtk_started_at, start)
  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
  if (Time.now - start) < 1
    @log.debug("#{sql} >> #{start.ago} / #{@conn.object_id}")
  else
    @log.info("#{sql} >> #{start.ago}")
  end
  out
end