Class: Gitlab::Database::TablesTruncate

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/database/tables_truncate.rb

Constant Summary collapse

GITLAB_SCHEMAS_TO_IGNORE =
%i[gitlab_geo gitlab_embedding].freeze

Instance Method Summary collapse

Constructor Details

#initialize(database_name:, min_batch_size: 5, logger: nil, until_table: nil, dry_run: false) ⇒ TablesTruncate

Returns a new instance of TablesTruncate.



8
9
10
11
12
13
14
# File 'lib/gitlab/database/tables_truncate.rb', line 8

def initialize(database_name:, min_batch_size: 5, logger: nil, until_table: nil, dry_run: false)
  @database_name = database_name
  @min_batch_size = min_batch_size
  @logger = logger
  @until_table = until_table
  @dry_run = dry_run
end

Instance Method Details

#executeObject



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
# File 'lib/gitlab/database/tables_truncate.rb', line 16

def execute
  raise "Cannot truncate legacy tables in single-db setup" if single_database_setup?
  raise "database is not supported" unless %w[main ci].include?(database_name)

  logger&.info "DRY RUN:" if dry_run

  tables_sorted = Gitlab::Database::TablesSortedByForeignKeys.new(connection, tables_to_truncate).execute
  # Checking if all the tables have the write-lock triggers
  # to make sure we are deleting the right tables on the right database.
  tables_sorted.flatten.each do |table_name|
    lock_writes_manager = Gitlab::Database::LockWritesManager.new(
      table_name: table_name,
      connection: connection,
      database_name: database_name,
      with_retries: true,
      logger: logger,
      dry_run: dry_run
    )

    unless lock_writes_manager.table_locked_for_writes?
      raise "Table '#{table_name}' is not locked for writes. Run the rake task gitlab:db:lock_writes first"
    end
  end

  if until_table
    table_index = tables_sorted.find_index { |tables_group| tables_group.include?(until_table) }
    raise "The table '#{until_table}' is not within the truncated tables" if table_index.nil?

    tables_sorted = tables_sorted[0..table_index]
  end

  # min_batch_size is the minimum number of new tables to truncate at each stage.
  # But in each stage we have also have to truncate the already truncated tables in the previous stages
  logger&.info "Truncating legacy tables for the database #{database_name}"
  truncate_tables_in_batches(tables_sorted)
end

#needs_truncation?Boolean

Returns:

  • (Boolean)


53
54
55
56
57
58
59
60
61
62
63
# File 'lib/gitlab/database/tables_truncate.rb', line 53

def needs_truncation?
  return false if single_database_setup?

  sql = tables_to_truncate.map { |table_name| "(SELECT EXISTS( SELECT * FROM #{table_name} ))" }.join("\nUNION\n")

  result = with_suppressed_query_analyzers do
    connection.execute(sql).to_a
  end

  result.to_a.any? { |row| row['exists'] == true }
end