Skip to content

Conversation

@aidanharan
Copy link
Contributor

@aidanharan aidanharan commented Apr 21, 2021

Coercing the FinderTest#test_include_on_unloaded_relation_with_having_referencing_aliased_select test as SQL Server does not support the SQL.

There is no point re-implementing the coerced test as its purpose is to test the HAVING clause referencing an aliased SELECT.

SQL Server

Author.select("COUNT(*) as total_posts", "authors.*").joins(:posts).group(:id).having("total_posts > 2").include?(bob)

SQL generated:

SELECT COUNT(*) as total_posts, authors.*
FROM [authors] 
INNER JOIN [posts] ON [posts].[author_id] = [authors].[id] 
GROUP BY [authors].[id] 
HAVING (total_posts > 2)

This SQL is invalid in SQL Server and throws the error Invalid column name 'total_posts'. There are 2 reasons why the SQL is invalid:

  • Cannot use SELECT alias total_posts in HAVING clause.
  • Cannot SELECT authors.* as the columns are not in the GROUP clause.

PostgreSQL
PostgreSQL skips this test (https://github.com/rails/rails/blob/d927db7eec984a980e5533dc307164e24c137690/activerecord/test/cases/finder_test.rb#L428) as it does not support the SQL.

SELECT COUNT(*) as total_posts, authors.* 
FROM "authors" 
INNER JOIN "posts" ON "posts"."author_id" = "authors"."id" 
GROUP BY "authors"."id" 
HAVING (total_posts > 2)

Error:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "total_posts" does not exist
LINE 1: ... = "authors"."id" GROUP BY "authors"."id" HAVING (total_post...

MySQL
Generates the following SQL which is valid in MySQL.

SELECT COUNT(*) as total_posts, authors.* 
FROM `authors` 
INNER JOIN `posts` ON `posts`.`author_id` = `authors`.`id` 
GROUP BY `authors`.`id` 
HAVING (total_posts > 2)

SQLite
Generates the following SQL which is valid in SQLite.

SELECT COUNT(*) as total_posts, authors.* 
FROM "authors" 
INNER JOIN "posts" ON "posts"."author_id" = "authors"."id" 
GROUP BY "authors"."id" 
HAVING (total_posts > 2)

@aidanharan aidanharan marked this pull request as ready for review April 21, 2021 13:50
@wpolicarpo wpolicarpo merged commit fea63a9 into rails-sqlserver:main Apr 21, 2021
lavika pushed a commit to lavika/activerecord-sqlserver-adapter that referenced this pull request Sep 26, 2023
Co-authored-by: Aidan Haran <aharan@fusioneer.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants