Module: Squirm::Core

Included in:
Squirm
Defined in:
lib/squirm/core.rb

Overview

The core DSL used by Squirm.

Instance Method Summary collapse

Instance Method Details

#connect(options = {}) ⇒ Object

Establishes a connection pool.

Parameters:

  • options (Hash) (defaults to: {})

    The connection options

Options Hash (options):

  • :pool (String)

    Use the given pool rather than Squirm’s.

  • :timeout (Fixnum)

    The pool timeout.

  • :pool_size (Fixnum)

    The pool size.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/squirm/core.rb', line 14

def connect(options = {})
  return @pool = options[:pool] if options[:pool]
  options   = options.dup
  timeout   = options.delete(:timeout) || 5
  pool_size = options.delete(:pool_size) || 1
  @pool     = Squirm::Pool.new(timeout)
  pool_size.times do
    conn = PGconn.open(options)
    yield conn if block_given?
    @pool.checkin conn
  end
end

#disconnectObject

Disconnects all pool connections and sets the pool to nil.



28
29
30
31
32
# File 'lib/squirm/core.rb', line 28

def disconnect
  return unless pool
  pool.map(&:close)
  @pool = nil
end

#exec(*args, &block) ⇒ Object

Executes the query and passes the result to the block you specify.



35
36
37
38
39
40
41
# File 'lib/squirm/core.rb', line 35

def exec(*args, &block)
  if current = Thread.current[:squirm_connection]
    current.exec(*args, &block)
  else
    use {|conn| conn.exec(*args, &block)}
  end
end

#poolSquirm::Pool

Gets the connection pool.

Returns:



45
46
47
# File 'lib/squirm/core.rb', line 45

def pool
  @pool if defined? @pool
end

#quote_ident(*args) ⇒ String

Quotes an SQL identifier.

Returns:

  • (String)

    The identifier.



82
83
84
# File 'lib/squirm/core.rb', line 82

def quote_ident(*args)
  PGconn.quote_ident(*args.map(&:to_s))
end

#rollbackObject

Rolls back from inside a #transaction block.

Raises:

  • (Rollback)


63
64
65
# File 'lib/squirm/core.rb', line 63

def rollback
  raise Rollback
end

#transactionObject

Performs a #use inside a transaction.



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/squirm/core.rb', line 50

def transaction
  use do |connection|
    connection.transaction do |conn|
      begin
        yield conn
      rescue Rollback
        return
      end
    end
  end
end

#useObject

Checks out a connection and uses it for all database access inside the block.



69
70
71
72
73
74
75
76
77
78
# File 'lib/squirm/core.rb', line 69

def use
  conn = @pool.checkout
  begin
    Thread.current[:squirm_connection] = conn
    yield conn
  ensure
    Thread.current[:squirm_connection] = nil
    @pool.checkin conn
  end
end