Welcome to mirror list, hosted at ThFree Co, Russian Federation.

database_helpers.rb « database « helpers « support « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f3b2a2a614737a485918104bef71fc3881248167 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 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.
    def swapout_view_for_table(view, connection: nil)
      connection ||= ActiveRecord::Base.connection

      connection.execute(<<~SQL.squish)
        CREATE TABLE #{view}_copy (LIKE #{view});
        DROP VIEW #{view};
        ALTER TABLE #{view}_copy RENAME TO #{view};
      SQL
    end

    # 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
    def with_statement_timeout(timeout)
      # 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

      previous_timeout = ActiveRecord::Base.connection
        .exec_query('SHOW statement_timeout')[0].fetch('statement_timeout')

      set_statement_timeout("#{timeout}ms")

      yield
    ensure
      begin
        set_statement_timeout(previous_timeout)
      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

    # Set statement timeout for the current transaction.
    #
    # Note, that it does not restore the previous statement timeout.
    # Use `with_statement_timeout` instead.
    #
    # @param timeout - Statement timeout in seconds
    #
    # Example:
    #
    #   set_statement_timeout(0.1)
    #   model.select('pg_sleep(0.11)')
    def set_statement_timeout(timeout)
      ActiveRecord::Base.connection.execute(
        format(%(SET LOCAL statement_timeout = '%s'), timeout)
      )
    end
  end
end