Class: Mysql2::StatementResult

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/mysql2/statement.rb

Instance Method Summary collapse

Constructor Details

#initialize(result, **opts) ⇒ StatementResult

Returns a new instance of StatementResult.



45
46
47
48
49
50
51
# File 'lib/mysql2/statement.rb', line 45

def initialize(result, **opts)
  if !opts[:cache_rows] && !opts[:stream]
    warn ':cache_rows is forced for prepared statements (if not streaming)'
  end
  @result = result
  @opts = opts
end

Instance Method Details

#convert_type(value, field, opts) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/mysql2/statement.rb', line 89

def convert_type(value, field, opts)
  return nil if value.nil?
  case field.type
  when Mysql::Field::TYPE_BIT
    opts[:cast_booleans] ? value != "\x00" : value
  when Mysql::Field::TYPE_TINY
    opts[:cast_booleans] && field.length == 1 ? value != 0 : value
  when Mysql::Field::TYPE_TIME
    Time.new(2000, 1, 1) + value
  else
    value
  end
end

#each(**opts, &block) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/mysql2/statement.rb', line 53

def each(**opts, &block)
  opts = @opts.merge(opts)

  raise Mysql2::Error, 'Result set has already been freed' if opts[:stream] && @all_retrieved
  return enum_for(:each, **opts) unless block

  @pos ||= 0
  @cached ||= []
  @pos = 0 unless opts[:stream]

  while @pos < @cached.size
    block.call @cached[@pos]
    @pos += 1
  end

  @result.data_seek @pos
  while (row = @result.fetch(**opts))
    row = @result.fields.map.with_index do |f, i|
      convert_type(row[i], f, opts)
    end
    if opts[:as] == :hash
      row = @result.fields.map.with_index.to_h do |f, i|
        key = opts[:symbolize_keys] ? f.name.intern : f.name
        [key, row[i]]
      end
    end
    @cached.push row if opts[:cache_rows]
    @pos += 1
    block.call row
  end
  @all_retrieved = true
  self
rescue Mysql::Error => e
  raise Mysql2::Error, e.message
end