Skip to content

Commit 6068805

Browse files
committed
Some SQL Server tests for string to binary and back. The #binary_to_string looks solid to me, removed TODO.
1 parent a50cd78 commit 6068805

File tree

3 files changed

+24
-13
lines changed

3 files changed

+24
-13
lines changed

lib/active_record/connection_adapters/sqlserver_adapter.rb

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -194,21 +194,12 @@ def string_to_time(value)
194194
super
195195
end
196196
end
197-
198-
# To insert into a SQL server binary column, the value must be
199-
# converted to hex characters and prepended with 0x
200-
# Example: INSERT into varbinarytable values (0x0)
201-
# See the output of the stored procedure: 'exec sp_datatype_info'
202-
# and note the literal prefix value of 0x for binary types
197+
203198
def string_to_binary(value)
204199
"0x#{value.unpack("H*")[0]}"
205200
end
206-
201+
207202
def binary_to_string(value)
208-
# Check if the value actually is hex output from the database
209-
# or an Active Record attribute that was just written. If hex, pack the hex
210-
# characters into a string, otherwise return the value
211-
# TODO: This conversion is asymmetrical, and could corrupt data if the original data looked like hex. We need to avoid the guesswork
212203
value =~ /[^[:xdigit:]]/ ? value : [value].pack('H*')
213204
end
214205

test/cases/adapter_test_sqlserver.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
class AdapterTestSqlserver < ActiveRecord::TestCase
66

7+
fixtures :binaries
8+
79
def setup
810
@connection = ActiveRecord::Base.connection
911
end
Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,32 @@
11
require 'cases/sqlserver_helper'
2+
require 'models/binary'
23

34
class ColumnTestSqlserver < ActiveRecord::TestCase
45

56
def setup
67
@column_klass = ActiveRecord::ConnectionAdapters::SQLServerColumn
78
end
89

9-
should 'be a placeholder' do
10-
assert true
10+
11+
context 'For :binary columns' do
12+
13+
setup do
14+
@binary_string = "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000\000!\371\004\000\000\000\000\000,\000\000\000\000\001\000\001\000\000\002\002D\001\000;"
15+
@saved_bdata = Binary.create!(:data => @binary_string)
16+
end
17+
18+
should 'read and write binary data equally' do
19+
assert_equal @binary_string, Binary.find(@saved_bdata).data
20+
end
21+
22+
should 'quote data for sqlserver with literal 0x prefix' do
23+
# See the output of the stored procedure: 'exec sp_datatype_info'
24+
sqlserver_encoded_bdata = "0x47494638396101000100800000ffffff00000021f90400000000002c00000000010001000002024401003b"
25+
assert_equal sqlserver_encoded_bdata, @column_klass.string_to_binary(@binary_string)
26+
end
27+
1128
end
1229

1330

31+
1432
end

0 commit comments

Comments
 (0)