Class: Mysql2Model::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/mysql2_model/client.rb

Overview

TODO:

Evented Connection Pool

multi-repository aware mysql2 client proxy

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(repos) ⇒ Object

Returns a multi-repository proxy.



6
7
8
# File 'lib/mysql2_model/client.rb', line 6

def initialize(repos)
  @repos = repos
end

Class Method Details

.[](repository_name) ⇒ Object

Repository accessor lazily instantiates Mysql2::Clients or delegates them to an instance of the multi-repository proxy



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mysql2_model/client.rb', line 45

def [](repository_name)
  if repository_name.is_a?(Array)
    self.new(repository_name)
  else
    load_repos
    @repositories[repository_name][:client] ||= begin
      c = Mysql2::Client.new(@repositories[repository_name][:config])
      c.query_options.merge!(:symbolize_keys => true)
      c
    end
  end
end

.[]=(repository_name, config) ⇒ Object

Repository accessor stores the connection parameters for later use



58
59
60
61
62
# File 'lib/mysql2_model/client.rb', line 58

def []=(repository_name,config)
  @repositories ||= {}
  @repositories[repository_name] ||= {}
  @repositories[repository_name][:config] = config
end

.load_repos(force = false) ⇒ Object

loads the repositories with the YAML object pointed to by Mysql2Model::Config.repository_path, subsequent calls are ignored unless forced.

Parameters:

  • force (boolean) (defaults to: false)

    Use force = true to reload the repositories and overwrite the existing Hash.



35
36
37
38
39
40
41
42
43
# File 'lib/mysql2_model/client.rb', line 35

def load_repos(force=false)
  unless force
    return unless @repositories.blank?
  end
  repos = YAML.load(File.new(Mysql2Model::Config.repository_path, 'r'))
  repos[:repositories].each do |repo, config|
    self[repo] = config 
  end
end

.repositoriesObject

Stores a collection of mysql2 connections



28
29
30
31
# File 'lib/mysql2_model/client.rb', line 28

def repositories
  load_repos
  @repositories 
end

Instance Method Details

#escape(statement) ⇒ Object

Use the first connection to execute a single escape

Parameters:

  • statement (String)

    MySQL statement



22
23
24
# File 'lib/mysql2_model/client.rb', line 22

def escape(statement)
  self.class[@repos.first].escape(statement)
end

#query(statement) ⇒ Object

Collect the results of a multi-repository query into a single resultset

Parameters:

  • statement (String)

    MySQL statement



11
12
13
14
15
16
17
18
19
# File 'lib/mysql2_model/client.rb', line 11

def query(statement)
  collection = []
  @repos.each do |repo|
    self.class[repo].query(statement).each do |row| 
      collection << row
    end
  end
  collection
end