From 6c4b435ae656f6649e976fcbc566e92a8507e853 Mon Sep 17 00:00:00 2001 From: Loic Nageleisen Date: Tue, 21 Nov 2017 11:19:48 +0100 Subject: [PATCH] Add support for LIMIT and OFFSET --- lib/rebel/sql.rb | 13 ++++++++++--- test/test_raw.rb | 8 ++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/rebel/sql.rb b/lib/rebel/sql.rb index 2e2f51d..0f59724 100644 --- a/lib/rebel/sql.rb +++ b/lib/rebel/sql.rb @@ -13,14 +13,16 @@ module Rebel::SQL exec(Rebel::SQL.drop_table(table_name)) end - def select(*fields, distinct: distinct, 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, limit: nil, offset: nil) exec(Rebel::SQL.select(*fields, distinct: distinct, from: from, where: where, inner: inner, left: left, - right: right)) + right: right, + limit: limit, + offset: offset)) end def insert_into(table_name, *rows) @@ -179,7 +181,7 @@ module Rebel::SQL SQL end - def select(*fields, distinct: nil, 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, limit: nil, offset: nil) raw <<-SQL SELECT #{distinct ? "DISTINCT #{names(*distinct)}" : names(*fields)} #{from?(from)} @@ -187,6 +189,7 @@ module Rebel::SQL #{left?(left)} #{right?(right)} #{where?(where)} + #{limit?(limit, offset)} SQL end @@ -350,5 +353,9 @@ module Rebel::SQL def right?(join) join ? "RIGHT #{join}" : nil end + + def limit?(limit, offset) + limit ? "LIMIT #{value(limit)}" << (offset ? " OFFSET #{offset}" : "") : nil + end end end diff --git a/test/test_raw.rb b/test/test_raw.rb index e938772..2b9f3c9 100644 --- a/test/test_raw.rb +++ b/test/test_raw.rb @@ -117,6 +117,14 @@ class TestRaw < Minitest::Test assert_str_equal(Rebel::SQL.select(distinct: [:bar, :baz], from: :foo).gsub(/\s+/, ' ').strip, 'SELECT DISTINCT "bar", "baz" FROM "foo"') end + def test_select_limit + assert_str_equal(Rebel::SQL.select(:bar, from: :foo, limit: 10).gsub(/\s+/, ' ').strip, 'SELECT "bar" FROM "foo" LIMIT 10') + end + + def test_select_offset + assert_str_equal(Rebel::SQL.select(:bar, from: :foo, limit: 10, offset: 20).gsub(/\s+/, ' ').strip, 'SELECT "bar" FROM "foo" LIMIT 10 OFFSET 20') + 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