2021-03-08 18:12:59 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Database
|
|
|
|
module DatabaseHelpers
|
|
|
|
# In order to directly work with views using factories,
|
|
|
|
# we can swapout the view for a table of identical structure.
|
2023-07-09 08:55:56 +05:30
|
|
|
def swapout_view_for_table(view, connection:, schema: nil)
|
|
|
|
table_name = [schema, "_test_#{view}_copy"].compact.join('.')
|
|
|
|
|
2022-08-13 15:12:31 +05:30
|
|
|
connection.execute(<<~SQL.squish)
|
2023-07-09 08:55:56 +05:30
|
|
|
CREATE TABLE #{table_name} (LIKE #{view});
|
2021-03-08 18:12:59 +05:30
|
|
|
DROP VIEW #{view};
|
2023-07-09 08:55:56 +05:30
|
|
|
ALTER TABLE #{table_name} RENAME TO #{view};
|
2021-03-08 18:12:59 +05:30
|
|
|
SQL
|
|
|
|
end
|
2021-04-17 20:07:23 +05:30
|
|
|
|
|
|
|
# Set statement timeout temporarily.
|
|
|
|
# Useful when testing query timeouts.
|
|
|
|
#
|
|
|
|
# Note that this method cannot restore the timeout if a query
|
|
|
|
# was canceled due to e.g. a statement timeout.
|
|
|
|
# Refrain from using this transaction in these situations.
|
|
|
|
#
|
|
|
|
# @param timeout - Statement timeout in seconds
|
|
|
|
#
|
|
|
|
# Example:
|
|
|
|
#
|
|
|
|
# with_statement_timeout(0.1) do
|
|
|
|
# model.select('pg_sleep(0.11)')
|
|
|
|
# end
|
2023-03-17 16:20:25 +05:30
|
|
|
def with_statement_timeout(timeout, connection:)
|
2021-04-17 20:07:23 +05:30
|
|
|
# Force a positive value and a minimum of 1ms for very small values.
|
|
|
|
timeout = (timeout * 1000).abs.ceil
|
|
|
|
|
|
|
|
raise ArgumentError, 'Using a timeout of `0` means to disable statement timeout.' if timeout == 0
|
|
|
|
|
2023-03-17 16:20:25 +05:30
|
|
|
previous_timeout = connection.select_value('SHOW statement_timeout')
|
2021-04-17 20:07:23 +05:30
|
|
|
|
2023-03-17 16:20:25 +05:30
|
|
|
connection.execute(format(%(SET LOCAL statement_timeout = '%s'), timeout))
|
2021-04-17 20:07:23 +05:30
|
|
|
|
|
|
|
yield
|
|
|
|
ensure
|
|
|
|
begin
|
2023-03-17 16:20:25 +05:30
|
|
|
connection.execute(format(%(SET LOCAL statement_timeout = '%s'), previous_timeout))
|
2021-04-17 20:07:23 +05:30
|
|
|
rescue ActiveRecord::StatementInvalid
|
|
|
|
# After a transaction was canceled/aborted due to e.g. a statement
|
|
|
|
# timeout commands are ignored and will raise in PG::InFailedSqlTransaction.
|
|
|
|
# We can safely ignore this error because the statement timeout was set
|
|
|
|
# for the currrent transaction which will be closed anyway.
|
|
|
|
end
|
|
|
|
end
|
2021-03-08 18:12:59 +05:30
|
|
|
end
|
|
|
|
end
|