class NoSE::Proxy::MysqlProxy

A proxy which speaks the MySQL protocol and executes queries

Public Class Methods

new(*args) click to toggle source
Calls superclass method NoSE::Proxy::ProxyBase::new
# File lib/nose/proxy/mysql.rb, line 9
def initialize(*args)
  super

  # Initialize a hash for the state of sockets
  @state = {}
end

Public Instance Methods

handle_connection(socket) click to toggle source

Authenticate the client and process queries

# File lib/nose/proxy/mysql.rb, line 17
def handle_connection(socket)
  return authenticate socket if @state[socket].nil?

  # Retrieve the saved state of the socket
  protocol = @state[socket]

  begin
    protocol.process_command(&method(:process_query))
  rescue ::Mysql::ClientError::ServerGoneError
    # Ensure the socket is closed and remove the state
    remove_connection socket
    return false
  end

  # Keep this socket around
  true
end
remove_connection(socket) click to toggle source

Remove the state of the socket

# File lib/nose/proxy/mysql.rb, line 36
def remove_connection(socket)
  socket.close
  @state.delete socket
end

Private Instance Methods

authenticate(socket) click to toggle source

Auth the client and prepare for query processsing @return [Boolean]

# File lib/nose/proxy/mysql.rb, line 45
def authenticate(socket)
  protocol = ::Mysql::ServerProtocol.new socket

  # Try to authenticate
  begin
    protocol.authenticate
  rescue
    remove_connection socket
    return false
  end

  @state[socket] = protocol

  true
end
process_query(protocol, query) click to toggle source

Execute the query on the backend and return the result

# File lib/nose/proxy/mysql.rb, line 62
def process_query(protocol, query)
  begin
    @logger.debug { "Got query #{query}" }
    result = query_result query
    @logger.debug "Executed query with #{result.size} results"
  rescue ParseFailed => exc
    protocol.error ::Mysql::ServerError::ER_PARSE_ERROR, exc.message
  rescue Backend::PlanNotFound => exc
    protocol.error ::Mysql::ServerError::ER_UNKNOWN_STMT_HANDLER,
                   exc.message
  end

  result
end
query_result(query) click to toggle source

Get the result of the query from the backend

# File lib/nose/proxy/mysql.rb, line 80
def query_result(query)
  query = Statement.parse query, @result.workload.model
  @backend.query(query).lazy.map do |row|
    Hash[query.select.map { |field| [field.name, row[field.id]] }]
  end
end