Skip to content

Commit 55aa57f

Browse files
committed
Better support for orders with an expression. Fixes #155. [Jason Frey, Joe Rafaniello]
* Use String#mb_chars in a few places just in case SQL is unicode and needed. * Added some Regexp foo (best I can) that allows functions with commas to pass through unmolested. Oh the days when Regexp's littered the whole adapter :)
1 parent 436a747 commit 55aa57f

File tree

4 files changed

+16
-4
lines changed

4 files changed

+16
-4
lines changed

CHANGELOG

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11

2+
* 3.1.5 *
3+
4+
* Better support for orders with an expression. Fixes #155. [Jason Frey, Joe Rafaniello]
5+
6+
27
* 3.1.4 *
38

49
* Use INFORMATION_SCHEMA.KEY_COLUMN_USAGE for schema reflection speed.

lib/active_record/connection_adapters/sqlserver/version.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ module ConnectionAdapters
33
module Sqlserver
44
module Version
55

6-
VERSION = '3.1.4'
6+
VERSION = '3.1.5'
77

88
end
99
end

lib/arel/visitors/sqlserver.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,10 @@ def order(*expr)
4141
x
4242
when String
4343
x.split(',').map do |s|
44+
s = x if x.strip =~ /\A\b\w+\b\(.*,.*\)(\s+(ASC|DESC))?\Z/i # Allow functions with comma(s) to pass thru.
4445
s.strip!
45-
d = s =~ /(asc|desc)$/i ? $1.upcase : nil
46-
e = d.nil? ? s : s[0...-d.length].strip
46+
d = s =~ /(ASC|DESC)\Z/i ? $1.upcase : nil
47+
e = d.nil? ? s : s.mb_chars[0...-d.length].strip
4748
e = Arel.sql(e)
4849
d && d == "DESC" ? Arel::Nodes::Descending.new(e) : Arel::Nodes::Ascending.new(e)
4950
end
@@ -204,7 +205,7 @@ def source_with_lock_for_select_statement(o)
204205
source = "FROM #{visit(core.source).strip}" if core.source
205206
if source && o.lock
206207
lock = visit o.lock
207-
index = source.match(/FROM [\w\[\]\.]+/)[0].length
208+
index = source.match(/FROM [\w\[\]\.]+/)[0].mb_chars.length
208209
source.insert index, " #{lock}"
209210
else
210211
source

test/cases/order_test_sqlserver.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,12 @@ class OrderTestSqlserver < ActiveRecord::TestCase
9999
assert_equal post1, Post.order(order).first
100100
end
101101

102+
should 'support inline function with parameters DESC' do
103+
order = "SUBSTRING(title, 1, 3) DESC"
104+
post1 = Post.create :title => 'ZZZ Post', :body => 'Test cased orders.'
105+
assert_equal post1, Post.order(order).first
106+
end
107+
102108
should 'support primary: inline function, secondary: column' do
103109
order = "LEN(title), body"
104110
post1 = Post.create :title => 'A', :body => 'AAA Test cased orders.'

0 commit comments

Comments
 (0)