Class: Mysql::Result

Inherits:
Object show all
Defined in:
lib/sequel_core/adapters/mysql.rb

Overview

Monkey patch Mysql::Result to yield hashes with symbol keys

Constant Summary collapse

MYSQL_TYPES =
{
  0   => :to_d,     # MYSQL_TYPE_DECIMAL
  #1   => :to_i,     # MYSQL_TYPE_TINY
  2   => :to_i,     # MYSQL_TYPE_SHORT
  3   => :to_i,     # MYSQL_TYPE_LONG
  4   => :to_f,     # MYSQL_TYPE_FLOAT
  5   => :to_f,     # MYSQL_TYPE_DOUBLE
  # 6   => ??,        # MYSQL_TYPE_NULL
  7   => :to_sequel_time,  # MYSQL_TYPE_TIMESTAMP
  8   => :to_i,     # MYSQL_TYPE_LONGLONG
  9   => :to_i,     # MYSQL_TYPE_INT24
  10  => :to_date,  # MYSQL_TYPE_DATE
  11  => :to_time,  # MYSQL_TYPE_TIME
  12  => :to_sequel_time,  # MYSQL_TYPE_DATETIME
  13  => :to_i,     # MYSQL_TYPE_YEAR
  14  => :to_date,  # MYSQL_TYPE_NEWDATE
  # 15  => :to_s      # MYSQL_TYPE_VARCHAR
  # 16  => :to_s,     # MYSQL_TYPE_BIT
  246 => :to_d,     # MYSQL_TYPE_NEWDECIMAL
  247 => :to_i,     # MYSQL_TYPE_ENUM
  248 => :to_i      # MYSQL_TYPE_SET
  # 249 => :to_s,     # MYSQL_TYPE_TINY_BLOB
  # 250 => :to_s,     # MYSQL_TYPE_MEDIUM_BLOB
  # 251 => :to_s,     # MYSQL_TYPE_LONG_BLOB
  # 252 => :to_s,     # MYSQL_TYPE_BLOB
  # 253 => :to_s,     # MYSQL_TYPE_VAR_STRING
  # 254 => :to_s,     # MYSQL_TYPE_STRING
  # 255 => :to_s      # MYSQL_TYPE_GEOMETRY
}

Instance Method Summary collapse

Instance Method Details

#columns(with_table = nil) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/sequel_core/adapters/mysql.rb', line 49

def columns(with_table = nil)
  unless @columns
    @column_types = []
    @columns = fetch_fields.map do |f|
      @column_types << f.type
      (with_table ? "#{f.table}.#{f.name}" : f.name).to_sym
    end
  end
  @columns
end

#convert_type(v, type) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/sequel_core/adapters/mysql.rb', line 35

def convert_type(v, type)
  if v
    if type == 1
      # We special case tinyint here to avoid adding
      # a method to an ancestor of Fixnum
      v.to_i == 0 ? false : true
    else
      (t = MYSQL_TYPES[type]) ? v.send(t) : v
    end
  else
    nil
  end
end

#each_array(with_table = nil) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/sequel_core/adapters/mysql.rb', line 60

def each_array(with_table = nil)
  c = columns
  while row = fetch_row
    c.each_with_index do |f, i|
      if (t = MYSQL_TYPES[@column_types[i]]) && (v = row[i])
        row[i] = v.send(t)
      end
    end
    yield row
  end
end

#each_hash(with_table = nil) ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/sequel_core/adapters/mysql.rb', line 72

def each_hash(with_table = nil)
  c = columns
  while row = fetch_row
    h = {}
    c.each_with_index {|f, i| h[f] = convert_type(row[i], @column_types[i])}
    yield h
  end
end