Class: DB::Context::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/db/context/session.rb

Overview

A connected context for sending queries and reading results.

Direct Known Subclasses

Transaction

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pool, **options) ⇒ Session

Initialize the query context attached to the given connection pool.



15
16
17
18
# File 'lib/db/context/session.rb', line 15

def initialize(pool, **options)
  @pool = pool
  @connection = nil
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



21
22
23
# File 'lib/db/context/session.rb', line 21

def connection
  @connection
end

#poolObject (readonly)

Returns the value of attribute pool.



20
21
22
# File 'lib/db/context/session.rb', line 20

def pool
  @pool
end

Instance Method Details

#call(statement, **options) ⇒ Object

Send a query to the server.



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/db/context/session.rb', line 61

def call(statement, **options)
  self.with_connection do |connection|
    connection.send_query(statement, **options)
    
    if block_given?
      yield connection
    elsif result = connection.next_result
      return Records.wrap(result)
    end
  end
end

#clause(fragment = String.new) ⇒ Object

Create a new query builder with an initial clause fragment.



90
91
92
93
94
# File 'lib/db/context/session.rb', line 90

def clause(fragment = String.new)
  with_connection do
    Query.new(self, fragment)
  end
end

#closeObject

Flush the connection and then return it to the connection pool.



29
30
31
32
33
34
# File 'lib/db/context/session.rb', line 29

def close
  if @connection
    @pool.release(@connection)
    @connection = nil
  end
end

#closed?Boolean

Check if the session connection is closed.



38
39
40
# File 'lib/db/context/session.rb', line 38

def closed?
  @connection.nil?
end

#connect!Object

Pin a connection to the current session.



24
25
26
# File 'lib/db/context/session.rb', line 24

def connect!
  @connection ||= @pool.acquire
end

#query(fragment = String.new, **parameters) ⇒ Object

Create a new query builder with optional initial fragment and parameters.



77
78
79
80
81
82
83
84
85
# File 'lib/db/context/session.rb', line 77

def query(fragment = String.new, **parameters)
  with_connection do
    if parameters.empty?
      Query.new(self, fragment)
    else
      Query.new(self).interpolate(fragment, **parameters)
    end
  end
end

#with_connection(&block) ⇒ Object

Execute a block with a database connection, acquiring one if necessary.



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/db/context/session.rb', line 45

def with_connection(&block)
  if @connection
    yield @connection
  else
    @pool.acquire do |connection|
      @connection = connection
      
      yield connection
    ensure
      @connection = nil
    end
  end
end