diff --git a/spec/db_spec.cr b/spec/db_spec.cr index d35db8b..1edb3fc 100644 --- a/spec/db_spec.cr +++ b/spec/db_spec.cr @@ -217,4 +217,21 @@ DB::DriverSpecs(MySql::Any).run do end end end + + it "allows VARBINARY fields to be read as slices" do |db| + db.exec %(create table if not exists btest (b varbinary(16) not null);) + db.exec %(insert into btest (b) values (X'5a5a5a');) + + DB.open db.uri do |db| + begin + db.query("select b from btest") do |rs| + rs.each do + rs.read(Bytes).should eq Bytes.new(3, 90_u8) + end + end + rescue e + fail("Expected no exception, but got \"#{e.message}\"") + end + end + end end diff --git a/src/mysql/result_set.cr b/src/mysql/result_set.cr index f2320c9..06c48bf 100644 --- a/src/mysql/result_set.cr +++ b/src/mysql/result_set.cr @@ -88,6 +88,18 @@ class MySql::ResultSet < DB::ResultSet end end + # In order not to break existing functionality expecting strings, we only + # apply the binary check if bytes are requested in the read method call + def read(t : Bytes.class) + val = read + + if val.is_a?(String) && @columns[@column_index - 1].character_set == 63 + val.to_slice + else + val + end + end + def read(t : Bool.class) MySql::Type.from_mysql(read.as(Int8)) end