DBSourceDBContextSession

class Session

A connected context for sending queries and reading results.

Definitions

def initialize(pool, **options)

Initialize the query context attached to the given connection pool.

Implementation

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

def connect!

Pin a connection to the current session.

Implementation

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

def close

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

Implementation

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

def closed?

Check if the session connection is closed.

Signature

returns Boolean

True if the connection is closed (nil), false otherwise.

Implementation

def closed?
	@connection.nil?
end

def with_connection(&block)

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

Signature

yields {|connection| ...}

The connection block.

parameter connection Object

The database connection object.

Implementation

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

def call(statement, **options)

Send a query to the server.

Signature

parameter statement String

The SQL query to send.

Implementation

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

def query(fragment = String.new, **parameters)

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

Signature

parameter fragment String

Initial SQL fragment for the query.

parameter parameters Hash

Parameters for interpolation into the fragment.

returns Query

A new query builder instance.

Implementation

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

def clause(fragment = String.new)

Create a new query builder with an initial clause fragment.

Signature

parameter fragment String

Initial SQL clause fragment.

returns Query

A new query builder instance.

Implementation

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