Skip to content

Commit

Permalink
fix binary data escaping for DB2
Browse files Browse the repository at this point in the history
  • Loading branch information
mluu committed Dec 17, 2012
1 parent c9dc409 commit f586c8a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
9 changes: 9 additions & 0 deletions lib/sequel/adapters/shared/db2.rb
Expand Up @@ -204,6 +204,7 @@ def uses_clob_for_text?
module DatasetMethods
include EmulateOffsetWithRowNumber

APOS = Dataset::APOS
PAREN_CLOSE = Dataset::PAREN_CLOSE
PAREN_OPEN = Dataset::PAREN_OPEN
BITWISE_METHOD_MAP = {:& =>:BITAND, :| => :BITOR, :^ => :BITXOR, :'B~'=>:BITNOT}
Expand All @@ -216,6 +217,9 @@ module DatasetMethods
FETCH_FIRST = " FETCH FIRST ".freeze
ROWS_ONLY = " ROWS ONLY".freeze
EMPTY_FROM_TABLE = ' FROM "SYSIBM"."SYSDUMMY1"'.freeze
HEX_START = 'X'.freeze
HSTAR = "H*".freeze
CAST_BLOB_OPEN = "BLOB(".freeze

# DB2 casts strings using RTRIM and CHAR instead of VARCHAR.
def cast_sql_append(sql, expr, type)
Expand Down Expand Up @@ -316,6 +320,11 @@ def literal_true
BOOL_TRUE
end

# DB2 uses a literal hexidecimal number for blob strings
def literal_blob_append(sql, v)
sql << CAST_BLOB_OPEN << HEX_START << APOS << v.unpack(HSTAR).first << APOS << PAREN_CLOSE
end

# Add a fallback table for empty from situation
def select_from_sql(sql)
@opts[:from] ? super : (sql << EMPTY_FROM_TABLE)
Expand Down
7 changes: 6 additions & 1 deletion spec/adapters/db2_spec.rb
Expand Up @@ -42,8 +42,8 @@
DB2_DB.create_table!(:items) do
Integer :id, :primary_key => true
Integer :number
File :bin_big
column :bin_string, 'varchar(20) for bit data'
column :bin_blob, 'blob'
end
end
let(:ds) { DB2_DB[:items] }
Expand All @@ -61,6 +61,11 @@
ds.insert(:id => 100, :number => 20)
ds.select_hash(:id, :number).should == {1 => 10, 100 => 20}
end

specify "should insert into binary columns" do
ds.insert(:id => 1, :bin_string => Sequel.blob("\1"), :bin_blob => Sequel.blob("\2"))
ds.select(:bin_string, :bin_blob).first.should == {:bin_string => "\1", :bin_blob => "\2"}
end
end

describe Sequel::Database do
Expand Down
2 changes: 1 addition & 1 deletion spec/integration/dataset_test.rb
Expand Up @@ -309,7 +309,7 @@
end
end

cspecify "should properly escape binary data", [:odbc], [:jdbc, :hsqldb], :oracle do
cspecify "should properly escape binary data", [:odbc], [:jdbc, :hsqldb], [:jdbc, :db2], :oracle do
INTEGRATION_DB.get(Sequel.cast(Sequel.blob("\1\2\3"), File).as(:a)).should == "\1\2\3"
end

Expand Down

0 comments on commit f586c8a

Please sign in to comment.