Skip to content

Commit

Permalink
fixed unprepared result set parsing (crystal-lang#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
benoist authored and bcardiff committed Jul 13, 2017
1 parent 6a6d38d commit b4fa995
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
20 changes: 20 additions & 0 deletions spec/db_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,24 @@ DB::DriverSpecs(MySql::Any).run do
fail("Expected no exception, but got \"#{e.message}\"")
end
end

it "allows unprepared statement queries" do |db|
db.exec %(create table if not exists a (i int not null, str text not null);)
db.exec %(insert into a (i, str) values (23, "bai bai");)

2.times do |i|
DB.open db.uri do |db|
begin
db.unprepared.query("SELECT i, str FROM a WHERE i = 23") do |rs|
rs.each do
rs.read(Int32).should eq 23
rs.read(String).should eq "bai bai"
end
end
rescue e
fail("Expected no exception, but got \"#{e.message}\"")
end
end
end
end
end
21 changes: 15 additions & 6 deletions src/mysql/text_result_set.cr
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class MySql::TextResultSet < DB::ResultSet

@conn : MySql::Connection
@row_packet : MySql::ReadPacket?
@header : UInt8
@first_byte : UInt8

def initialize(statement, column_count)
super(statement)
Expand All @@ -16,8 +16,9 @@ class MySql::TextResultSet < DB::ResultSet

@column_index = 0 # next column index to return

@header = 0u8
@first_byte = 0u8
@eof_reached = false
@first_row_packet = false
end

def do_close
Expand All @@ -41,13 +42,14 @@ class MySql::TextResultSet < DB::ResultSet

@row_packet = row_packet = @conn.build_read_packet

@header = row_packet.read_byte!
if @header == 0xfe # EOF
@first_byte = row_packet.read_byte!
if @first_byte == 0xfe # EOF
@eof_reached = true
return false
end

@column_index = 0
@first_row_packet = true
# TODO remove row_packet.read(@null_bitmap_slice)
return true
end
Expand All @@ -63,13 +65,20 @@ class MySql::TextResultSet < DB::ResultSet
def read
row_packet = @row_packet.not_nil!

is_nil = @header == 0xfb
if @first_row_packet
current_byte = @first_byte
@first_row_packet = false
else
current_byte = row_packet.read_byte!
end

is_nil = current_byte == 0xfb
col = @column_index
@column_index += 1
if is_nil
nil
else
length = row_packet.read_lenenc_int(@header)
length = row_packet.read_lenenc_int(current_byte)
val = row_packet.read_string(length)
val = @columns[col].column_type.parse(val)

Expand Down

0 comments on commit b4fa995

Please sign in to comment.