From adfa38baea125012784877045a292d18488638ac Mon Sep 17 00:00:00 2001 From: Loic Nageleisen Date: Tue, 21 Nov 2017 11:17:29 +0100 Subject: [PATCH] Add support for DISTINCT --- lib/rebel/sql.rb | 7 ++++--- test/test_raw.rb | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/rebel/sql.rb b/lib/rebel/sql.rb index 9379fdc..2e2f51d 100644 --- a/lib/rebel/sql.rb +++ b/lib/rebel/sql.rb @@ -13,8 +13,9 @@ module Rebel::SQL exec(Rebel::SQL.drop_table(table_name)) end - def select(*fields, from: nil, where: nil, inner: nil, left: nil, right: nil) + def select(*fields, distinct: distinct, from: nil, where: nil, inner: nil, left: nil, right: nil) exec(Rebel::SQL.select(*fields, + distinct: distinct, from: from, where: where, inner: inner, @@ -178,9 +179,9 @@ module Rebel::SQL SQL end - def select(*fields, from: nil, where: nil, inner: nil, left: nil, right: nil) + def select(*fields, distinct: nil, from: nil, where: nil, inner: nil, left: nil, right: nil) raw <<-SQL - SELECT #{names(*fields)} + SELECT #{distinct ? "DISTINCT #{names(*distinct)}" : names(*fields)} #{from?(from)} #{inner?(inner)} #{left?(left)} diff --git a/test/test_raw.rb b/test/test_raw.rb index b19aee1..e938772 100644 --- a/test/test_raw.rb +++ b/test/test_raw.rb @@ -109,6 +109,14 @@ class TestRaw < Minitest::Test assert_str_equal(Rebel::SQL.select(Rebel::SQL.raw('1')).strip, 'SELECT 1') end + def test_select_distinct + assert_str_equal(Rebel::SQL.select(distinct: :bar, from: :foo).gsub(/\s+/, ' ').strip, 'SELECT DISTINCT "bar" FROM "foo"') + end + + def test_select_distinct_multiple + assert_str_equal(Rebel::SQL.select(distinct: [:bar, :baz], from: :foo).gsub(/\s+/, ' ').strip, 'SELECT DISTINCT "bar", "baz" FROM "foo"') + end + def test_nested_select assert_str_equal(Rebel::SQL.select(Rebel::SQL.raw('*'), from: Rebel::SQL.name(:foo), where: Rebel::SQL.name(:bar).in(Rebel::SQL.select(Rebel::SQL.name(:bar), from: Rebel::SQL.name(:foo)))).gsub(/\s+/, ' ').strip, 'SELECT * FROM "foo" WHERE "bar" IN ( SELECT "bar" FROM "foo" )') end