Skip to content

Commit

Permalink
Properly quote autogenerated column aliases
Browse files Browse the repository at this point in the history
Fix: #43878
  • Loading branch information
byroot committed Dec 17, 2021
1 parent 4607108 commit 7e6e909
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 1 deletion.
16 changes: 16 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,19 @@
* Fix quoting of column aliases generated by calculation methods.

Since the alias is derived from the table name, we can't assume the result
is a valid identifier.

```ruby
class Test < ActiveRecord::Base
self.table_name = '1abc'
end
Test.group(:id).count
# syntax error at or near "1" (ActiveRecord::StatementInvalid)
# LINE 1: SELECT COUNT(*) AS count_all, "1abc"."id" AS 1abc_id FROM "1...
```

*Jean Boussier*

* Add `authenticate_by` when using `has_secure_password`.

`authenticate_by` is intended to replace code like the following, which
Expand Down
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/relation/calculations.rb
Expand Up @@ -345,12 +345,13 @@ def execute_grouped_calculation(operation, column_name, distinct) # :nodoc:
column = aggregate_column(column_name)
column_alias = column_alias_for("#{operation} #{column_name.to_s.downcase}")
select_value = operation_over_aggregate_column(column, operation, distinct)
select_value.as(column_alias)
select_value.as(connection.quote_column_name(column_alias))

select_values = [select_value]
select_values += self.select_values unless having_clause.empty?

select_values.concat group_columns.map { |aliaz, field|
aliaz = connection.quote_column_name(aliaz)
if field.respond_to?(:as)
field.as(aliaz)
else
Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Expand Up @@ -12,6 +12,7 @@
require "models/topic"
require "models/reply"
require "models/numeric_data"
require "models/need_quoting"
require "models/minivan"
require "models/speedometer"
require "models/ship_part"
Expand Down Expand Up @@ -1380,4 +1381,10 @@ def test_count_with_block_and_column_name_raises_an_error
end
end
end

test "group alias is properly quoted" do
assert_nothing_raised do
NeedQuoting.group(:name).count
end
end
end
2 changes: 2 additions & 0 deletions activerecord/test/fixtures/1_need_quoting.yml
@@ -0,0 +1,2 @@
- name: Foo
- name: Bar
5 changes: 5 additions & 0 deletions activerecord/test/models/need_quoting.rb
@@ -0,0 +1,5 @@
# frozen_string_literal: true

class NeedQuoting < ActiveRecord::Base
self.table_name = "1_need_quoting"
end
4 changes: 4 additions & 0 deletions activerecord/test/schema/schema.rb
Expand Up @@ -8,6 +8,10 @@
# #
# ------------------------------------------------------------------- #

create_table :"1_need_quoting", force: true do |t|
t.string :name
end

create_table :accounts, force: true do |t|
t.references :firm, index: false
t.string :firm_name
Expand Down

0 comments on commit 7e6e909

Please sign in to comment.