From 7161e2b79146a6c379d6429c3178c7e7f113c43b Mon Sep 17 00:00:00 2001 From: miguelff Date: Wed, 20 Sep 2017 17:45:23 +0200 Subject: [PATCH] Adds `SQL.transaction` To add support for running queries inside an `ActiveRecord::Base.transaction` scope --- lib/github/sql.rb | 7 +++++++ test/github/sql_test.rb | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/github/sql.rb b/lib/github/sql.rb index d631ea7..d5a54ef 100644 --- a/lib/github/sql.rb +++ b/lib/github/sql.rb @@ -67,6 +67,13 @@ module GitHub end end + # Public: Run inside a transaction + def self.transaction + ActiveRecord::Base.connection.transaction do + yield + end + end + # Public: Instantiate a literal SQL value. # # WARNING: The given value is LITERALLY inserted into your SQL without being diff --git a/test/github/sql_test.rb b/test/github/sql_test.rb index 0405cb6..3daaf58 100644 --- a/test/github/sql_test.rb +++ b/test/github/sql_test.rb @@ -147,6 +147,30 @@ class GitHub::SQLTest < Minitest::Test refute_includes sql.query, "foo" end + def test_transaction + GitHub::SQL.run("CREATE TEMPORARY TABLE affected_rows_test (x INT)") + + begin + GitHub::SQL.transaction do + GitHub::SQL.run("INSERT INTO affected_rows_test VALUES (1), (2)") + GitHub::SQL.run("INSERT INTO affected_rows_test VALUES (3), (4)") + raise "BOOM" + end + rescue => e + assert_equal 0, GitHub::SQL.new("Select count(*) from affected_rows_test").value + else + fail + end + + GitHub::SQL.transaction do + GitHub::SQL.run("INSERT INTO affected_rows_test VALUES (1), (2)") + GitHub::SQL.run("INSERT INTO affected_rows_test VALUES (3), (4)") + end + assert_equal 4, GitHub::SQL.new("Select count(*) from affected_rows_test").value + ensure + GitHub::SQL.run("DROP TABLE affected_rows_test") + end + def test_literal assert_kind_of GitHub::SQL::Literal, GitHub::SQL::LITERAL("foo") end