Skip to content

Fix ambiguous ORDER BY clauses by fully qualifying column names #452

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion lib/closure_tree/numeric_order_support.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def reorder_with_parent_id(parent_id, minimum_sort_order_value = nil)
UPDATE #{quoted_table_name}
SET #{quoted_order_column(false)} = t.seq + #{minimum_sort_order_value.to_i - 1}
FROM (
SELECT #{quoted_id_column_name} AS id, row_number() OVER(ORDER BY #{order_by}) AS seq
SELECT #{quoted_id_column_name} AS id, row_number() OVER(ORDER BY #{fully_qualified_order_by}) AS seq
FROM #{quoted_table_name}
WHERE #{where_eq(parent_column_name, parent_id)} #{min_where}
) AS t
Expand Down
6 changes: 3 additions & 3 deletions lib/closure_tree/support.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ def hierarchy_table_name

def with_order_option(opts)
if order_option?
opts[:order] = [opts[:order], order_by].compact.join(",")
opts[:order] = [opts[:order], fully_qualified_order_by].compact.join(",")
end
opts
end

def scope_with_order(scope, additional_order_by = nil)
if order_option?
scope.order(*([additional_order_by, order_by].compact))
scope.order(*([additional_order_by, fully_qualified_order_by].compact))
else
additional_order_by ? scope.order(additional_order_by) : scope
end
Expand All @@ -85,7 +85,7 @@ def has_many_order_without_option(order_by_opt)
end

def has_many_order_with_option(order_by_opt=nil)
order_options = [order_by_opt, order_by].compact
order_options = [order_by_opt, fully_qualified_order_by].compact
[lambda {
order_options = order_options.map { |o| o.is_a?(Proc) ? o.call : o }
order(order_options)
Expand Down
4 changes: 4 additions & 0 deletions lib/closure_tree/support_attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ def quoted_order_column(include_table_name = true)
"#{prefix}#{connection.quote_column_name(order_column)}"
end

def fully_qualified_order_by
"#{quoted_order_column} #{order_by_order}"
end

# table_name alias keyword , like "AS". When used on table name alias, Oracle Database don't support used 'AS'
def t_alias_keyword
(ActiveRecord::Base.connection.adapter_name.to_sym == :OracleEnhanced) ? "" : "AS"
Expand Down