Skip to content
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

Changing how the select_count method counts returned rows. #687

Merged
merged 1 commit into from
Jun 17, 2021
Merged
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
13 changes: 6 additions & 7 deletions spec/queryable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -765,14 +765,13 @@ describe Avram::Queryable do
query.select_count.should eq 1
end

it "raises when used with offset or limit" do
expect_raises(Avram::UnsupportedQueryError) do
UserQuery.new.limit(1).select_count
end
Comment on lines -768 to -771
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can now use a limit and offset in the select_count queries. The reason you couldn't before was because SELECT COUNT() would always ever return 1 row. So it didn't make sense to have a limit or offset. Now with this sub-select way, you can use limit to your advantage.

Say you have a table with 7 records in it. If you do a limit 10, and then run a count, you'll get 7. Do the same thing once there's 12 records in the table, and then you'll only get 10. It's sort of like an upper bounds check.

it "works with distinct_on" do
UserFactory.new.age(30).create
UserFactory.new.age(30).create

expect_raises(Avram::UnsupportedQueryError) do
UserQuery.new.offset(1).select_count
end
query = UserQuery.new.distinct_on(&.age)

query.select_count.should eq 1
end

it "returns 0 if postgres returns no results" do
Expand Down
5 changes: 4 additions & 1 deletion src/avram/queryable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,10 @@ module Avram::Queryable(T)
end

def select_count : Int64
exec_scalar(&.select_count).as(Int64)
table = "(#{query.statement}) AS temp"
new_query = Avram::QueryBuilder.new(table).select_count
Comment on lines +199 to +200
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be cleared up if we implemented #682

result = database.scalar new_query.statement, args: query.args, queryable: schema_class.name
result.as(Int64)
rescue e : DB::NoResultsError
0_i64
end
Expand Down