Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow users to read bytes for BINARY and VARBINARY columns #59

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions spec/db_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 14 additions & 0 deletions src/mysql/result_set.cr
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,20 @@ 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 | (Bytes | Nil)).class)
val = read

if !val
nil
elsif val.is_a?(String | Bytes)
val.to_slice
else
raise "#{self.class}#read returned a #{val.class}. A #{t} was expected."
end
end

def read(t : Bool.class)
MySql::Type.from_mysql(read.as(Int8))
end
Expand Down