Skip to content

Instantly share code, notes, and snippets.

@johnnymo87
Created May 2, 2015 01:00
Show Gist options
  • Save johnnymo87/004a5d17dc874141eb9f to your computer and use it in GitHub Desktop.
Save johnnymo87/004a5d17dc874141eb9f to your computer and use it in GitHub Desktop.
WITH RECURSIVE
require 'spec_helper'
describe 'WITH RECURSIVE' do
# http://www.postgresql.org/docs/8.4/static/queries-with.html
# http://www.cybertec.at/common-mistakes-union-vs-union-all/
def query(n)
ActiveRecord::Base.connection.exec_query(
<<-SQL
WITH RECURSIVE one_to_inf(n) AS (
VALUES (1)
UNION ALL
SELECT n+1 FROM one_to_inf
),
take AS (
SELECT n FROM one_to_inf LIMIT #{n}
)
SELECT sum(n)
FROM take
SQL
)
end
it "(1..(1.0/0.0)).take(100).sum" do
expect(
query(100).to_hash
).to eq([
{ "sum" => "5050" },
])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment