Last active
May 28, 2024 08:43
-
-
Save moofkit/8e06c237ca282a3aeb8d7bc6d144ed9a to your computer and use it in GitHub Desktop.
ActiveRecord alter default timeout for PostgreSQL query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
class << self | |
# Start a new transaction with a statement timeout. | |
# The timeout is reset after the block is executed. Works even with pg_bouncer in transaction mode | |
# This is useful for queries that are expected to be slower than the default timeout | |
# timeout - the timeout in seconds | |
# Usage: | |
# with_statement_timeout(10) do | |
# Model.find_by_sql("SELECT pg_sleep(20)") | |
# end | |
def with_statement_timeout(timeout) | |
timeout_ms = (timeout.seconds * 1000).to_i | |
transaction(requires_new: true) do | |
connection.exec_query(sanitize_sql_array(["SET LOCAL statement_timeout TO ?", timeout_ms])) | |
yield | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment