Skip to content

Commit ad4eeb2

Browse files
committed
Document two methods for avoiding N'' quoting on char/varchar columns.
1 parent 0894cf6 commit ad4eeb2

File tree

4 files changed

+31
-5
lines changed

4 files changed

+31
-5
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#### Fixed
44

55
* Undefined method `database_prefix_remote_server?' Fixes #450. Thanks @jippeholwerda
6+
* Document two methods for avoiding N'' quoting on char/varchar columns.
67

78

89
## v4.2.10

lib/active_record/connection_adapters/sqlserver/quoting.rb

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,10 @@ def _quote(value)
5454
case value
5555
when Type::Binary::Data
5656
"0x#{value.hex}"
57+
when ActiveRecord::Type::SQLServer::Char::Data
58+
value.quoted
5759
when String, ActiveSupport::Multibyte::Chars
58-
if value.is_utf8?
59-
"#{QUOTED_STRING_PREFIX}#{super}"
60-
else
61-
super
62-
end
60+
"#{QUOTED_STRING_PREFIX}#{super}"
6361
else
6462
super
6563
end

lib/active_record/connection_adapters/sqlserver/type/char.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,18 @@ def type
88
:char
99
end
1010

11+
class Data
12+
13+
def initialize(value)
14+
@value = value.to_s
15+
end
16+
17+
def quoted
18+
"'#{@value}'"
19+
end
20+
21+
end
22+
1123
end
1224
end
1325
end

test/cases/specific_schema_test_sqlserver.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,21 @@ class SpecificSchemaTestSQLServer < ActiveRecord::TestCase
107107
assert_equal r, SSTestEdgeSchema.where('crazy]]quote' => 'crazyqoute').first
108108
end
109109

110+
it 'various methods to bypass national quoted columns for any column, but primarily useful for char/varchar' do
111+
value = Class.new do
112+
def quoted_id
113+
"'T'"
114+
end
115+
end
116+
# Using ActiveRecord's quoted_id feature for objects.
117+
assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(char_col: value.new).first }
118+
assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(varchar_col: value.new).first }
119+
# Using our custom char type data.
120+
data = ActiveRecord::Type::SQLServer::Char::Data
121+
assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(char_col: data.new('T')).first }
122+
assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(varchar_col: data.new('T')).first }
123+
end
124+
110125
# With column names that have spaces
111126

112127
it 'create record using a custom attribute reader and be able to load it back in' do

0 commit comments

Comments
 (0)