Class: Baza::Driver::Mysql

Inherits:
BaseSqlDriver show all
Defined in:
lib/baza/drivers/mysql.rb

Defined Under Namespace

Classes: Column, Columns, Index, Indexes, Result, Sqlspecs, Table, Tables, UnbufferedResult

Instance Attribute Summary collapse

Attributes inherited from BaseSqlDriver

#baza, #cols, #indexes, #sep_col, #sep_table, #sep_val, #tables

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseSqlDriver

#esc_col, #escape

Constructor Details

#initialize(baza) ⇒ Mysql

Returns a new instance of Mysql.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/baza/drivers/mysql.rb', line 20

def initialize(baza)
  super

  @opts = @baza.opts

  require 'monitor'
  @mutex = Monitor.new

  if baza.opts[:conn]
    @conn = baza.opts[:conn]
  else
    if @opts[:encoding]
      @encoding = @opts[:encoding]
    else
      @encoding = 'utf8'
    end

    if @baza.opts.key?(:port)
      @port = @baza.opts[:port].to_i
    else
      @port = 3306
    end

    reconnect
  end
end

Instance Attribute Details

#connObject (readonly)

Returns the value of attribute conn.



14
15
16
# File 'lib/baza/drivers/mysql.rb', line 14

def conn
  @conn
end

Class Method Details

.from_object(args) ⇒ Object



16
17
18
# File 'lib/baza/drivers/mysql.rb', line 16

def self.from_object(args)
  raise 'Mysql does not support auth extraction' if args[:object].class.name == 'Mysql'
end

Instance Method Details

#cleanObject

Cleans the wref-map holding the tables.



58
59
60
# File 'lib/baza/drivers/mysql.rb', line 58

def clean
  tables.clean if tables
end

#closeObject

Closes the connection threadsafe.



117
118
119
# File 'lib/baza/drivers/mysql.rb', line 117

def close
  @mutex.synchronize { @conn.close }
end

#destroyObject

Destroyes the connection.



122
123
124
125
126
127
128
129
130
# File 'lib/baza/drivers/mysql.rb', line 122

def destroy
  @conn = nil
  @baza = nil
  @mutex = nil
  @subtype = nil
  @encoding = nil
  @query_args = nil
  @port = nil
end

#escape_alternative(string) ⇒ Object

Escapes a string to be safe to use in a query.



107
108
109
# File 'lib/baza/drivers/mysql.rb', line 107

def escape_alternative(string)
  return @conn.escape_string(string.to_s)
end

#insert_multi(tablename, arr_hashes, args = nil) ⇒ Object

Inserts multiple rows in a table. Can return the inserted IDs if asked to in arguments.



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/baza/drivers/mysql.rb', line 133

def insert_multi(tablename, arr_hashes, args = nil)
  sql = "INSERT INTO `#{tablename}` ("

  first = true
  if args && args[:keys]
    keys = args[:keys]
  elsif arr_hashes.first.is_a?(Hash)
    keys = arr_hashes.first.keys
  else
    raise "Could not figure out keys."
  end

  keys.each do |col_name|
    sql << "," unless first
    first = false if first
    sql << "`#{self.esc_col(col_name)}`"
  end

  sql << ") VALUES ("

  first = true
  arr_hashes.each do |hash|
    if first
      first = false
    else
      sql << "),("
    end

    first_key = true
    if hash.is_a?(Array)
      hash.each do |val|
        if first_key
          first_key = false
        else
          sql << ","
        end

        sql << @baza.sqlval(val)
      end
    else
      hash.each do |key, val|
        if first_key
          first_key = false
        else
          sql << ","
        end

        sql << @baza.sqlval(val)
      end
    end
  end

  sql << ")"

  return sql if args && args[:return_sql]

  self.query(sql)

  if args && args[:return_id]
    first_id = self.last_id
    raise "Invalid ID: #{first_id}" if first_id.to_i <= 0
    ids = [first_id]
    1.upto(arr_hashes.length - 1) do |count|
      ids << first_id + count
    end

    ids_length = ids.length
    arr_hashes_length = arr_hashes.length
    raise "Invalid length (#{ids_length}, #{arr_hashes_length})." unless ids_length == arr_hashes_length

    return ids
  else
    return nil
  end
end

#java_mysql_resultset_killer(id) ⇒ Object

This method handels the closing of statements and results for the Java MySQL-mode.



48
49
50
51
52
53
54
55
# File 'lib/baza/drivers/mysql.rb', line 48

def java_mysql_resultset_killer(id)
  data = @java_rs_data[id]
  return nil unless data

  data[:res].close
  data[:stmt].close
  @java_rs_data.delete(id)
end

#last_idObject

Returns the last inserted ID for the connection.



112
113
114
# File 'lib/baza/drivers/mysql.rb', line 112

def last_id
  @mutex.synchronize { return @conn.insert_id.to_i }
end

#query(str) ⇒ Object

Executes a query and returns the result.



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/baza/drivers/mysql.rb', line 72

def query(str)
  str = str.to_s
  str = str.force_encoding("UTF-8") if @encoding == "utf8" and str.respond_to?(:force_encoding)
  tries = 0

  begin
    tries += 1
    @mutex.synchronize do
      return Baza::Driver::Mysql::Result.new(self, @conn.query(str))
    end
  rescue => e
    if tries <= 3
      if e.message == "MySQL server has gone away" || e.message == "closed MySQL connection" or e.message == "Can't connect to local MySQL server through socket"
        sleep 0.5
        reconnect
        retry
      elsif e.message.include?("No operations allowed after connection closed") or e.message == "This connection is still waiting for a result, try again once you have the result" or e.message == "Lock wait timeout exceeded; try restarting transaction"
        reconnect
        retry
      end
    end

    raise e
  end
end

#query_ubuf(str) ⇒ Object

Executes an unbuffered query and returns the result that can be used to access the data.



99
100
101
102
103
104
# File 'lib/baza/drivers/mysql.rb', line 99

def query_ubuf(str)
  @mutex.synchronize do
    @conn.query_with_result = false
    return Baza::Driver::Mysql::UnbufferedResult.new(@conn, @opts, @conn.query(str))
  end
end

#reconnectObject

Respawns the connection to the MySQL-database.



63
64
65
66
67
68
69
# File 'lib/baza/drivers/mysql.rb', line 63

def reconnect
  @mutex.synchronize do
    require 'mysql' unless ::Object.const_defined?(:Mysql)
    @conn = ::Mysql.real_connect(@baza.opts[:host], @baza.opts[:user], @baza.opts[:pass], @baza.opts[:db], @port)
    query("SET NAMES '#{self.esc(@encoding)}'") if @encoding
  end
end

#transactionObject



209
210
211
212
213
214
215
216
217
218
219
# File 'lib/baza/drivers/mysql.rb', line 209

def transaction
  @baza.q("START TRANSACTION")

  begin
    yield @baza
    @baza.q("COMMIT")
  rescue
    @baza.q("ROLLBACK")
    raise
  end
end