Module: Faulty::Patch::Mysql2

Includes:
Base
Defined in:
lib/faulty/patch/mysql2.rb

Overview

Patch Mysql2 to run connections and queries in a circuit

This module is not required by default

Pass a :faulty key into your MySQL connection options to enable circuit protection. See circuit_from_hash for the available options.

COMMIT, ROLLBACK, and RELEASE SAVEPOINT queries are intentionally not protected by the circuit. This is to allow open transactions to be closed if possible.

Examples:

require 'faulty/patch/mysql2'

mysql = Mysql2::Client.new(host: '127.0.0.1', faulty: {})
mysql.query('SELECT * FROM users') # raises Faulty::CircuitError if connection fails

# If the faulty key is not given, no circuit is used
mysql = Mysql2::Client.new(host: '127.0.0.1')
mysql.query('SELECT * FROM users') # not protected by a circuit

See Also:

Constant Summary collapse

QUERY_WHITELIST =
[
  %r{\A(?:/\*.*?\*/)?\s*ROLLBACK}i,
  %r{\A(?:/\*.*?\*/)?\s*COMMIT}i,
  %r{\A(?:/\*.*?\*/)?\s*RELEASE\s+SAVEPOINT}i
].freeze

Instance Method Summary collapse

Methods included from Base

#faulty_run

Instance Method Details

#connect(*args) ⇒ Object

Protect the initial connnection


67
68
69
# File 'lib/faulty/patch/mysql2.rb', line 67

def connect(*args)
  faulty_run { super }
end

#initialize(opts = {}) ⇒ Object


45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/faulty/patch/mysql2.rb', line 45

def initialize(opts = {})
  @faulty_circuit = Patch.circuit_from_hash(
    'mysql2',
    opts[:faulty],
    errors: [
      ::Mysql2::Error::ConnectionError,
      ::Mysql2::Error::TimeoutError
    ],
    patched_error_module: Faulty::Patch::Mysql2
  )

  super
end

#pingObject

Protect manual connection pings


60
61
62
63
64
# File 'lib/faulty/patch/mysql2.rb', line 60

def ping
  faulty_run { super }
rescue Faulty::Patch::Mysql2::FaultyError
  false
end

#query(*args) ⇒ Object

Protect queries unless they are whitelisted


72
73
74
75
76
# File 'lib/faulty/patch/mysql2.rb', line 72

def query(*args)
  return super if QUERY_WHITELIST.any? { |r| !r.match(args.first).nil? }

  faulty_run { super }
end