logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

migration_helpers.rb (36261B)


  1. # frozen_string_literal: true
  2. # This file is copied almost entirely from GitLab, which has done a large
  3. # amount of work to ensure that migrations can happen with minimal downtime.
  4. # Many thanks to those engineers.
  5. # Changes have been made to remove dependencies on other GitLab files and to
  6. # shorten temporary column names.
  7. # Documentation on using these functions (and why one might do so):
  8. # https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/development/what_requires_downtime.md
  9. # The file itself:
  10. # https://gitlab.com/gitlab-org/gitlab-ce/blob/master/lib/gitlab/database/migration_helpers.rb
  11. # It is licensed as follows:
  12. # Copyright (c) 2011-2017 GitLab B.V.
  13. # Permission is hereby granted, free of charge, to any person obtaining a copy
  14. # of this software and associated documentation files (the "Software"), to deal
  15. # in the Software without restriction, including without limitation the rights
  16. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. # copies of the Software, and to permit persons to whom the Software is
  18. # furnished to do so, subject to the following conditions:
  19. # The above copyright notice and this permission notice shall be included in
  20. # all copies or substantial portions of the Software.
  21. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. # THE SOFTWARE.
  28. # This is bad form, but there are enough differences that it's impractical to do
  29. # otherwise:
  30. # rubocop:disable all
  31. module Mastodon
  32. module MigrationHelpers
  33. # Stub for Database.postgresql? from GitLab
  34. def self.postgresql?
  35. ActiveRecord::Base.configurations[Rails.env]['adapter'].casecmp('postgresql').zero?
  36. end
  37. # Stub for Database.mysql? from GitLab
  38. def self.mysql?
  39. ActiveRecord::Base.configurations[Rails.env]['adapter'].casecmp('mysql2').zero?
  40. end
  41. # Model that can be used for querying permissions of a SQL user.
  42. class Grant < ActiveRecord::Base
  43. self.table_name =
  44. if Mastodon::MigrationHelpers.postgresql?
  45. 'information_schema.role_table_grants'
  46. else
  47. 'mysql.user'
  48. end
  49. def self.scope_to_current_user
  50. if Mastodon::MigrationHelpers.postgresql?
  51. where('grantee = user')
  52. else
  53. where("CONCAT(User, '@', Host) = current_user()")
  54. end
  55. end
  56. # Returns true if the current user can create and execute triggers on the
  57. # given table.
  58. def self.create_and_execute_trigger?(table)
  59. priv =
  60. if Mastodon::MigrationHelpers.postgresql?
  61. where(privilege_type: 'TRIGGER', table_name: table)
  62. else
  63. where(Trigger_priv: 'Y')
  64. end
  65. priv.scope_to_current_user.any?
  66. end
  67. end
  68. BACKGROUND_MIGRATION_BATCH_SIZE = 1000 # Number of rows to process per job
  69. BACKGROUND_MIGRATION_JOB_BUFFER_SIZE = 1000 # Number of jobs to bulk queue at a time
  70. # Gets an estimated number of rows for a table
  71. def estimate_rows_in_table(table_name)
  72. exec_query('SELECT reltuples FROM pg_class WHERE relname = ' +
  73. "'#{table_name}'").to_a.first['reltuples']
  74. end
  75. # Adds `created_at` and `updated_at` columns with timezone information.
  76. #
  77. # This method is an improved version of Rails' built-in method `add_timestamps`.
  78. #
  79. # Available options are:
  80. # default - The default value for the column.
  81. # null - When set to `true` the column will allow NULL values.
  82. # The default is to not allow NULL values.
  83. def add_timestamps_with_timezone(table_name, **options)
  84. options[:null] = false if options[:null].nil?
  85. [:created_at, :updated_at].each do |column_name|
  86. if options[:default] && transaction_open?
  87. raise '`add_timestamps_with_timezone` with default value cannot be run inside a transaction. ' \
  88. 'You can disable transactions by calling `disable_ddl_transaction!` ' \
  89. 'in the body of your migration class'
  90. end
  91. # If default value is presented, use `add_column_with_default` method instead.
  92. if options[:default]
  93. add_column_with_default(
  94. table_name,
  95. column_name,
  96. :datetime_with_timezone,
  97. default: options[:default],
  98. allow_null: options[:null]
  99. )
  100. else
  101. add_column(table_name, column_name, :datetime_with_timezone, options)
  102. end
  103. end
  104. end
  105. # Creates a new index, concurrently when supported
  106. #
  107. # On PostgreSQL this method creates an index concurrently, on MySQL this
  108. # creates a regular index.
  109. #
  110. # Example:
  111. #
  112. # add_concurrent_index :users, :some_column
  113. #
  114. # See Rails' `add_index` for more info on the available arguments.
  115. def add_concurrent_index(table_name, column_name, **options)
  116. if transaction_open?
  117. raise 'add_concurrent_index can not be run inside a transaction, ' \
  118. 'you can disable transactions by calling disable_ddl_transaction! ' \
  119. 'in the body of your migration class'
  120. end
  121. if MigrationHelpers.postgresql?
  122. options = options.merge({ algorithm: :concurrently })
  123. disable_statement_timeout
  124. end
  125. add_index(table_name, column_name, options)
  126. end
  127. # Removes an existed index, concurrently when supported
  128. #
  129. # On PostgreSQL this method removes an index concurrently.
  130. #
  131. # Example:
  132. #
  133. # remove_concurrent_index :users, :some_column
  134. #
  135. # See Rails' `remove_index` for more info on the available arguments.
  136. def remove_concurrent_index(table_name, column_name, **options)
  137. if transaction_open?
  138. raise 'remove_concurrent_index can not be run inside a transaction, ' \
  139. 'you can disable transactions by calling disable_ddl_transaction! ' \
  140. 'in the body of your migration class'
  141. end
  142. if supports_drop_index_concurrently?
  143. options = options.merge({ algorithm: :concurrently })
  144. disable_statement_timeout
  145. end
  146. remove_index(table_name, options.merge({ column: column_name }))
  147. end
  148. # Removes an existing index, concurrently when supported
  149. #
  150. # On PostgreSQL this method removes an index concurrently.
  151. #
  152. # Example:
  153. #
  154. # remove_concurrent_index :users, "index_X_by_Y"
  155. #
  156. # See Rails' `remove_index` for more info on the available arguments.
  157. def remove_concurrent_index_by_name(table_name, index_name, **options)
  158. if transaction_open?
  159. raise 'remove_concurrent_index_by_name can not be run inside a transaction, ' \
  160. 'you can disable transactions by calling disable_ddl_transaction! ' \
  161. 'in the body of your migration class'
  162. end
  163. if supports_drop_index_concurrently?
  164. options = options.merge({ algorithm: :concurrently })
  165. disable_statement_timeout
  166. end
  167. remove_index(table_name, options.merge({ name: index_name }))
  168. end
  169. # Only available on Postgresql >= 9.2
  170. def supports_drop_index_concurrently?
  171. return false unless MigrationHelpers.postgresql?
  172. version = select_one("SELECT current_setting('server_version_num') AS v")['v'].to_i
  173. version >= 90200
  174. end
  175. # Adds a foreign key with only minimal locking on the tables involved.
  176. #
  177. # This method only requires minimal locking when using PostgreSQL. When
  178. # using MySQL this method will use Rails' default `add_foreign_key`.
  179. #
  180. # source - The source table containing the foreign key.
  181. # target - The target table the key points to.
  182. # column - The name of the column to create the foreign key on.
  183. # on_delete - The action to perform when associated data is removed,
  184. # defaults to "CASCADE".
  185. def add_concurrent_foreign_key(source, target, column:, on_delete: :cascade, target_col: 'id')
  186. # Transactions would result in ALTER TABLE locks being held for the
  187. # duration of the transaction, defeating the purpose of this method.
  188. if transaction_open?
  189. raise 'add_concurrent_foreign_key can not be run inside a transaction'
  190. end
  191. # While MySQL does allow disabling of foreign keys it has no equivalent
  192. # of PostgreSQL's "VALIDATE CONSTRAINT". As a result we'll just fall
  193. # back to the normal foreign key procedure.
  194. if MigrationHelpers.mysql?
  195. return add_foreign_key(source, target,
  196. column: column,
  197. on_delete: on_delete)
  198. else
  199. on_delete = 'SET NULL' if on_delete == :nullify
  200. end
  201. disable_statement_timeout
  202. key_name = concurrent_foreign_key_name(source, column, target_col)
  203. # Using NOT VALID allows us to create a key without immediately
  204. # validating it. This means we keep the ALTER TABLE lock only for a
  205. # short period of time. The key _is_ enforced for any newly created
  206. # data.
  207. execute <<-EOF.strip_heredoc
  208. ALTER TABLE #{source}
  209. ADD CONSTRAINT #{key_name}
  210. FOREIGN KEY (#{column})
  211. REFERENCES #{target} (#{target_col})
  212. #{on_delete ? "ON DELETE #{on_delete.upcase}" : ''}
  213. NOT VALID;
  214. EOF
  215. # Validate the existing constraint. This can potentially take a very
  216. # long time to complete, but fortunately does not lock the source table
  217. # while running.
  218. execute("ALTER TABLE #{source} VALIDATE CONSTRAINT #{key_name};")
  219. end
  220. # Returns the name for a concurrent foreign key.
  221. #
  222. # PostgreSQL constraint names have a limit of 63 bytes. The logic used
  223. # here is based on Rails' foreign_key_name() method, which unfortunately
  224. # is private so we can't rely on it directly.
  225. def concurrent_foreign_key_name(table, column, target_col)
  226. "fk_#{Digest::SHA256.hexdigest("#{table}_#{column}_#{target_col}_fk").first(10)}"
  227. end
  228. # Long-running migrations may take more than the timeout allowed by
  229. # the database. Disable the session's statement timeout to ensure
  230. # migrations don't get killed prematurely. (PostgreSQL only)
  231. def disable_statement_timeout
  232. execute('SET statement_timeout TO 0') if MigrationHelpers.postgresql?
  233. end
  234. # Updates the value of a column in batches.
  235. #
  236. # This method updates the table in batches of 5% of the total row count.
  237. # This method will continue updating rows until no rows remain.
  238. #
  239. # When given a block this method will yield two values to the block:
  240. #
  241. # 1. An instance of `Arel::Table` for the table that is being updated.
  242. # 2. The query to run as an Arel object.
  243. #
  244. # By supplying a block one can add extra conditions to the queries being
  245. # executed. Note that the same block is used for _all_ queries.
  246. #
  247. # Example:
  248. #
  249. # update_column_in_batches(:projects, :foo, 10) do |table, query|
  250. # query.where(table[:some_column].eq('hello'))
  251. # end
  252. #
  253. # This would result in this method updating only rows where
  254. # `projects.some_column` equals "hello".
  255. #
  256. # table - The name of the table.
  257. # column - The name of the column to update.
  258. # value - The value for the column.
  259. #
  260. # Rubocop's Metrics/AbcSize metric is disabled for this method as Rubocop
  261. # determines this method to be too complex while there's no way to make it
  262. # less "complex" without introducing extra methods (which actually will
  263. # make things _more_ complex).
  264. #
  265. # rubocop: disable Metrics/AbcSize
  266. def update_column_in_batches(table_name, column, value)
  267. if transaction_open?
  268. raise 'update_column_in_batches can not be run inside a transaction, ' \
  269. 'you can disable transactions by calling disable_ddl_transaction! ' \
  270. 'in the body of your migration class'
  271. end
  272. table = Arel::Table.new(table_name)
  273. total = estimate_rows_in_table(table_name).to_i
  274. if total == 0
  275. count_arel = table.project(Arel.star.count.as('count'))
  276. count_arel = yield table, count_arel if block_given?
  277. total = exec_query(count_arel.to_sql).to_hash.first['count'].to_i
  278. return if total == 0
  279. end
  280. # Update in batches of 5% until we run out of any rows to update.
  281. batch_size = ((total / 100.0) * 5.0).ceil
  282. max_size = 1000
  283. # The upper limit is 1000 to ensure we don't lock too many rows. For
  284. # example, for "merge_requests" even 1% of the table is around 35 000
  285. # rows for GitLab.com.
  286. batch_size = max_size if batch_size > max_size
  287. start_arel = table.project(table[:id]).order(table[:id].asc).take(1)
  288. start_arel = yield table, start_arel if block_given?
  289. first_row = exec_query(start_arel.to_sql).to_hash.first
  290. # In case there are no rows but we didn't catch it in the estimated size:
  291. return unless first_row
  292. start_id = first_row['id'].to_i
  293. say "Migrating #{table_name}.#{column} (~#{total.to_i} rows)"
  294. started_time = Time.now
  295. last_time = Time.now
  296. migrated = 0
  297. loop do
  298. stop_row = nil
  299. suppress_messages do
  300. stop_arel = table.project(table[:id])
  301. .where(table[:id].gteq(start_id))
  302. .order(table[:id].asc)
  303. .take(1)
  304. .skip(batch_size)
  305. stop_arel = yield table, stop_arel if block_given?
  306. stop_row = exec_query(stop_arel.to_sql).to_hash.first
  307. update_arel = Arel::UpdateManager.new
  308. .table(table)
  309. .set([[table[column], value]])
  310. .where(table[:id].gteq(start_id))
  311. if stop_row
  312. stop_id = stop_row['id'].to_i
  313. start_id = stop_id
  314. update_arel = update_arel.where(table[:id].lt(stop_id))
  315. end
  316. update_arel = yield table, update_arel if block_given?
  317. execute(update_arel.to_sql)
  318. end
  319. migrated += batch_size
  320. if Time.now - last_time > 1
  321. status = "Migrated #{migrated} rows"
  322. percentage = 100.0 * migrated / total
  323. status += " (~#{sprintf('%.2f', percentage)}%, "
  324. remaining_time = (100.0 - percentage) * (Time.now - started_time) / percentage
  325. status += "#{(remaining_time / 60).to_i}:"
  326. status += sprintf('%02d', remaining_time.to_i % 60)
  327. status += ' remaining, '
  328. # Tell users not to interrupt if we're almost done.
  329. if remaining_time > 10
  330. status += 'safe to interrupt'
  331. else
  332. status += 'DO NOT interrupt'
  333. end
  334. status += ')'
  335. say status, true
  336. last_time = Time.now
  337. end
  338. # There are no more rows left to update.
  339. break unless stop_row
  340. end
  341. end
  342. # Adds a column with a default value without locking an entire table.
  343. #
  344. # This method runs the following steps:
  345. #
  346. # 1. Add the column with a default value of NULL.
  347. # 2. Change the default value of the column to the specified value.
  348. # 3. Update all existing rows in batches.
  349. # 4. Set a `NOT NULL` constraint on the column if desired (the default).
  350. #
  351. # These steps ensure a column can be added to a large and commonly used
  352. # table without locking the entire table for the duration of the table
  353. # modification.
  354. #
  355. # table - The name of the table to update.
  356. # column - The name of the column to add.
  357. # type - The column type (e.g. `:integer`).
  358. # default - The default value for the column.
  359. # limit - Sets a column limit. For example, for :integer, the default is
  360. # 4-bytes. Set `limit: 8` to allow 8-byte integers.
  361. # allow_null - When set to `true` the column will allow NULL values, the
  362. # default is to not allow NULL values.
  363. #
  364. # This method can also take a block which is passed directly to the
  365. # `update_column_in_batches` method.
  366. def add_column_with_default(table, column, type, default:, limit: nil, allow_null: false, &block)
  367. if transaction_open?
  368. raise 'add_column_with_default can not be run inside a transaction, ' \
  369. 'you can disable transactions by calling disable_ddl_transaction! ' \
  370. 'in the body of your migration class'
  371. end
  372. disable_statement_timeout
  373. transaction do
  374. if limit
  375. add_column(table, column, type, default: nil, limit: limit)
  376. else
  377. add_column(table, column, type, default: nil)
  378. end
  379. # Changing the default before the update ensures any newly inserted
  380. # rows already use the proper default value.
  381. change_column_default(table, column, default)
  382. end
  383. begin
  384. update_column_in_batches(table, column, default, &block)
  385. change_column_null(table, column, false) unless allow_null
  386. # We want to rescue _all_ exceptions here, even those that don't inherit
  387. # from StandardError.
  388. rescue Exception => error # rubocop: disable all
  389. remove_column(table, column)
  390. raise error
  391. end
  392. end
  393. # Renames a column without requiring downtime.
  394. #
  395. # Concurrent renames work by using database triggers to ensure both the
  396. # old and new column are in sync. However, this method will _not_ remove
  397. # the triggers or the old column automatically; this needs to be done
  398. # manually in a post-deployment migration. This can be done using the
  399. # method `cleanup_concurrent_column_rename`.
  400. #
  401. # table - The name of the database table containing the column.
  402. # old - The old column name.
  403. # new - The new column name.
  404. # type - The type of the new column. If no type is given the old column's
  405. # type is used.
  406. def rename_column_concurrently(table, old, new, type: nil)
  407. if transaction_open?
  408. raise 'rename_column_concurrently can not be run inside a transaction'
  409. end
  410. check_trigger_permissions!(table)
  411. trigger_name = rename_trigger_name(table, old, new)
  412. # If we were in the middle of update_column_in_batches, we should remove
  413. # the old column and start over, as we have no idea where we were.
  414. if column_for(table, new)
  415. if MigrationHelpers.postgresql?
  416. remove_rename_triggers_for_postgresql(table, trigger_name)
  417. else
  418. remove_rename_triggers_for_mysql(trigger_name)
  419. end
  420. remove_column(table, new)
  421. end
  422. old_col = column_for(table, old)
  423. new_type = type || old_col.type
  424. col_opts = {
  425. precision: old_col.precision,
  426. scale: old_col.scale,
  427. }
  428. # We may be trying to reset the limit on an integer column type, so let
  429. # Rails handle that.
  430. unless [:bigint, :integer].include?(new_type)
  431. col_opts[:limit] = old_col.limit
  432. end
  433. add_column(table, new, new_type, col_opts)
  434. # We set the default value _after_ adding the column so we don't end up
  435. # updating any existing data with the default value. This isn't
  436. # necessary since we copy over old values further down.
  437. change_column_default(table, new, old_col.default) if old_col.default
  438. quoted_table = quote_table_name(table)
  439. quoted_old = quote_column_name(old)
  440. quoted_new = quote_column_name(new)
  441. if MigrationHelpers.postgresql?
  442. install_rename_triggers_for_postgresql(trigger_name, quoted_table,
  443. quoted_old, quoted_new)
  444. else
  445. install_rename_triggers_for_mysql(trigger_name, quoted_table,
  446. quoted_old, quoted_new)
  447. end
  448. update_column_in_batches(table, new, Arel::Table.new(table)[old])
  449. change_column_null(table, new, false) unless old_col.null
  450. copy_indexes(table, old, new)
  451. copy_foreign_keys(table, old, new)
  452. end
  453. # Changes the type of a column concurrently.
  454. #
  455. # table - The table containing the column.
  456. # column - The name of the column to change.
  457. # new_type - The new column type.
  458. def change_column_type_concurrently(table, column, new_type)
  459. temp_column = rename_column_name(column)
  460. rename_column_concurrently(table, column, temp_column, type: new_type)
  461. # Primary keys don't necessarily have an associated index.
  462. if ActiveRecord::Base.get_primary_key(table) == column.to_s
  463. old_pk_index_name = "index_#{table}_on_#{column}"
  464. new_pk_index_name = "index_#{table}_on_#{column}_cm"
  465. unless indexes_for(table, column).find{|i| i.name == old_pk_index_name}
  466. add_concurrent_index(table, [temp_column], {
  467. unique: true,
  468. name: new_pk_index_name
  469. })
  470. end
  471. end
  472. end
  473. # Performs cleanup of a concurrent type change.
  474. #
  475. # table - The table containing the column.
  476. # column - The name of the column to change.
  477. # new_type - The new column type.
  478. def cleanup_concurrent_column_type_change(table, column)
  479. temp_column = rename_column_name(column)
  480. # Wait for the indices to be built
  481. indexes_for(table, column).each do |index|
  482. expected_name = index.name + '_cm'
  483. puts "Waiting for index #{expected_name}"
  484. sleep 1 until indexes_for(table, temp_column).find {|i| i.name == expected_name }
  485. end
  486. was_primary = (ActiveRecord::Base.get_primary_key(table) == column.to_s)
  487. old_default_fn = column_for(table, column).default_function
  488. old_fks = []
  489. if was_primary
  490. # Get any foreign keys pointing at this column we need to recreate, and
  491. # remove the old ones.
  492. # Based on code from:
  493. # http://errorbank.blogspot.com/2011/03/list-all-foreign-keys-references-for.html
  494. old_fks_res = execute <<-EOF.strip_heredoc
  495. select m.relname as src_table,
  496. (select a.attname
  497. from pg_attribute a
  498. where a.attrelid = m.oid
  499. and a.attnum = o.conkey[1]
  500. and a.attisdropped = false) as src_col,
  501. o.conname as name,
  502. o.confdeltype as on_delete
  503. from pg_constraint o
  504. left join pg_class f on f.oid = o.confrelid
  505. left join pg_class c on c.oid = o.conrelid
  506. left join pg_class m on m.oid = o.conrelid
  507. where o.contype = 'f'
  508. and o.conrelid in (
  509. select oid from pg_class c where c.relkind = 'r')
  510. and f.relname = '#{table}';
  511. EOF
  512. old_fks = old_fks_res.to_a
  513. old_fks.each do |old_fk|
  514. add_concurrent_foreign_key(
  515. old_fk['src_table'],
  516. table,
  517. column: old_fk['src_col'],
  518. target_col: temp_column,
  519. on_delete: extract_foreign_key_action(old_fk['on_delete'])
  520. )
  521. remove_foreign_key(old_fk['src_table'], name: old_fk['name'])
  522. end
  523. end
  524. # If there was a sequence owned by the old column, make it owned by the
  525. # new column, as it will otherwise be deleted when we get rid of the
  526. # old column.
  527. if (seq_match = /^nextval\('([^']*)'(::text|::regclass)?\)/.match(old_default_fn))
  528. seq_name = seq_match[1]
  529. execute("ALTER SEQUENCE #{seq_name} OWNED BY #{table}.#{temp_column}")
  530. end
  531. transaction do
  532. # This has to be performed in a transaction as otherwise we might have
  533. # inconsistent data.
  534. cleanup_concurrent_column_rename(table, column, temp_column)
  535. rename_column(table, temp_column, column)
  536. # If there was an old default function, we didn't copy it. Do that now
  537. # in the transaction, so we don't miss anything.
  538. change_column_default(table, column, -> { old_default_fn }) if old_default_fn
  539. end
  540. # Rename any indices back to what they should be.
  541. indexes_for(table, column).each do |index|
  542. next unless index.name.end_with?('_cm')
  543. real_index_name = index.name.sub(/_cm$/, '')
  544. rename_index(table, index.name, real_index_name)
  545. end
  546. # Rename any foreign keys back to names based on the real column.
  547. foreign_keys_for(table, column).each do |fk|
  548. old_fk_name = concurrent_foreign_key_name(fk.from_table, temp_column, 'id')
  549. new_fk_name = concurrent_foreign_key_name(fk.from_table, column, 'id')
  550. execute("ALTER TABLE #{fk.from_table} RENAME CONSTRAINT " +
  551. "#{old_fk_name} TO #{new_fk_name}")
  552. end
  553. # Rename any foreign keys from other tables to names based on the real
  554. # column.
  555. old_fks.each do |old_fk|
  556. old_fk_name = concurrent_foreign_key_name(old_fk['src_table'],
  557. old_fk['src_col'], temp_column)
  558. new_fk_name = concurrent_foreign_key_name(old_fk['src_table'],
  559. old_fk['src_col'], column)
  560. execute("ALTER TABLE #{old_fk['src_table']} RENAME CONSTRAINT " +
  561. "#{old_fk_name} TO #{new_fk_name}")
  562. end
  563. # If the old column was a primary key, mark the new one as a primary key.
  564. if was_primary
  565. execute("ALTER TABLE #{table} ADD PRIMARY KEY USING INDEX " +
  566. "index_#{table}_on_#{column}")
  567. end
  568. end
  569. # Cleans up a concurrent column name.
  570. #
  571. # This method takes care of removing previously installed triggers as well
  572. # as removing the old column.
  573. #
  574. # table - The name of the database table.
  575. # old - The name of the old column.
  576. # new - The name of the new column.
  577. def cleanup_concurrent_column_rename(table, old, new)
  578. trigger_name = rename_trigger_name(table, old, new)
  579. check_trigger_permissions!(table)
  580. if MigrationHelpers.postgresql?
  581. remove_rename_triggers_for_postgresql(table, trigger_name)
  582. else
  583. remove_rename_triggers_for_mysql(trigger_name)
  584. end
  585. remove_column(table, old)
  586. end
  587. # Performs a concurrent column rename when using PostgreSQL.
  588. def install_rename_triggers_for_postgresql(trigger, table, old, new)
  589. execute <<-EOF.strip_heredoc
  590. CREATE OR REPLACE FUNCTION #{trigger}()
  591. RETURNS trigger AS
  592. $BODY$
  593. BEGIN
  594. NEW.#{new} := NEW.#{old};
  595. RETURN NEW;
  596. END;
  597. $BODY$
  598. LANGUAGE 'plpgsql'
  599. VOLATILE
  600. EOF
  601. execute <<-EOF.strip_heredoc
  602. CREATE TRIGGER #{trigger}
  603. BEFORE INSERT OR UPDATE
  604. ON #{table}
  605. FOR EACH ROW
  606. EXECUTE PROCEDURE #{trigger}()
  607. EOF
  608. end
  609. # Installs the triggers necessary to perform a concurrent column rename on
  610. # MySQL.
  611. def install_rename_triggers_for_mysql(trigger, table, old, new)
  612. execute <<-EOF.strip_heredoc
  613. CREATE TRIGGER #{trigger}_insert
  614. BEFORE INSERT
  615. ON #{table}
  616. FOR EACH ROW
  617. SET NEW.#{new} = NEW.#{old}
  618. EOF
  619. execute <<-EOF.strip_heredoc
  620. CREATE TRIGGER #{trigger}_update
  621. BEFORE UPDATE
  622. ON #{table}
  623. FOR EACH ROW
  624. SET NEW.#{new} = NEW.#{old}
  625. EOF
  626. end
  627. # Removes the triggers used for renaming a PostgreSQL column concurrently.
  628. def remove_rename_triggers_for_postgresql(table, trigger)
  629. execute("DROP TRIGGER IF EXISTS #{trigger} ON #{table}")
  630. execute("DROP FUNCTION IF EXISTS #{trigger}()")
  631. end
  632. # Removes the triggers used for renaming a MySQL column concurrently.
  633. def remove_rename_triggers_for_mysql(trigger)
  634. execute("DROP TRIGGER IF EXISTS #{trigger}_insert")
  635. execute("DROP TRIGGER IF EXISTS #{trigger}_update")
  636. end
  637. # Returns the (base) name to use for triggers when renaming columns.
  638. def rename_trigger_name(table, old, new)
  639. 'trigger_' + Digest::SHA256.hexdigest("#{table}_#{old}_#{new}").first(12)
  640. end
  641. # Returns the name to use for temporary rename columns.
  642. def rename_column_name(base)
  643. base.to_s + '_cm'
  644. end
  645. # Returns an Array containing the indexes for the given column
  646. def indexes_for(table, column)
  647. column = column.to_s
  648. indexes(table).select { |index| index.columns.include?(column) }
  649. end
  650. # Returns an Array containing the foreign keys for the given column.
  651. def foreign_keys_for(table, column)
  652. column = column.to_s
  653. foreign_keys(table).select { |fk| fk.column == column }
  654. end
  655. # Copies all indexes for the old column to a new column.
  656. #
  657. # table - The table containing the columns and indexes.
  658. # old - The old column.
  659. # new - The new column.
  660. def copy_indexes(table, old, new)
  661. old = old.to_s
  662. new = new.to_s
  663. indexes_for(table, old).each do |index|
  664. new_columns = index.columns.map do |column|
  665. column == old ? new : column
  666. end
  667. # This is necessary as we can't properly rename indexes such as
  668. # "ci_taggings_idx".
  669. name = index.name + '_cm'
  670. # If the order contained the old column, map it to the new one.
  671. order = index.orders
  672. if order.key?(old)
  673. order[new] = order.delete(old)
  674. end
  675. options = {
  676. unique: index.unique,
  677. name: name,
  678. length: index.lengths,
  679. order: order
  680. }
  681. # These options are not supported by MySQL, so we only add them if
  682. # they were previously set.
  683. options[:using] = index.using if index.using
  684. options[:where] = index.where if index.where
  685. add_concurrent_index(table, new_columns, options)
  686. end
  687. end
  688. # Copies all foreign keys for the old column to the new column.
  689. #
  690. # table - The table containing the columns and indexes.
  691. # old - The old column.
  692. # new - The new column.
  693. def copy_foreign_keys(table, old, new)
  694. foreign_keys_for(table, old).each do |fk|
  695. add_concurrent_foreign_key(fk.from_table,
  696. fk.to_table,
  697. column: new,
  698. on_delete: fk.on_delete)
  699. end
  700. end
  701. # Returns the column for the given table and column name.
  702. def column_for(table, name)
  703. name = name.to_s
  704. columns(table).find { |column| column.name == name }
  705. end
  706. # This will replace the first occurance of a string in a column with
  707. # the replacement
  708. # On postgresql we can use `regexp_replace` for that.
  709. # On mysql we find the location of the pattern, and overwrite it
  710. # with the replacement
  711. def replace_sql(column, pattern, replacement)
  712. quoted_pattern = Arel::Nodes::Quoted.new(pattern.to_s)
  713. quoted_replacement = Arel::Nodes::Quoted.new(replacement.to_s)
  714. if MigrationHelpers.mysql?
  715. locate = Arel::Nodes::NamedFunction
  716. .new('locate', [quoted_pattern, column])
  717. insert_in_place = Arel::Nodes::NamedFunction
  718. .new('insert', [column, locate, pattern.size, quoted_replacement])
  719. Arel::Nodes::SqlLiteral.new(insert_in_place.to_sql)
  720. else
  721. replace = Arel::Nodes::NamedFunction
  722. .new("regexp_replace", [column, quoted_pattern, quoted_replacement])
  723. Arel::Nodes::SqlLiteral.new(replace.to_sql)
  724. end
  725. end
  726. def remove_foreign_key_without_error(*args)
  727. remove_foreign_key(*args)
  728. rescue ArgumentError
  729. end
  730. def sidekiq_queue_migrate(queue_from, to:)
  731. while sidekiq_queue_length(queue_from) > 0
  732. Sidekiq.redis do |conn|
  733. conn.rpoplpush "queue:#{queue_from}", "queue:#{to}"
  734. end
  735. end
  736. end
  737. def sidekiq_queue_length(queue_name)
  738. Sidekiq.redis do |conn|
  739. conn.llen("queue:#{queue_name}")
  740. end
  741. end
  742. def check_trigger_permissions!(table)
  743. unless Grant.create_and_execute_trigger?(table)
  744. dbname = ActiveRecord::Base.configurations[Rails.env]['database']
  745. user = ActiveRecord::Base.configurations[Rails.env]['username'] || ENV['USER']
  746. raise <<-EOF
  747. Your database user is not allowed to create, drop, or execute triggers on the
  748. table #{table}.
  749. If you are using PostgreSQL you can solve this by logging in to the GitLab
  750. database (#{dbname}) using a super user and running:
  751. ALTER #{user} WITH SUPERUSER
  752. For MySQL you instead need to run:
  753. GRANT ALL PRIVILEGES ON *.* TO #{user}@'%'
  754. Both queries will grant the user super user permissions, ensuring you don't run
  755. into similar problems in the future (e.g. when new tables are created).
  756. EOF
  757. end
  758. end
  759. # Bulk queues background migration jobs for an entire table, batched by ID range.
  760. # "Bulk" meaning many jobs will be pushed at a time for efficiency.
  761. # If you need a delay interval per job, then use `queue_background_migration_jobs_by_range_at_intervals`.
  762. #
  763. # model_class - The table being iterated over
  764. # job_class_name - The background migration job class as a string
  765. # batch_size - The maximum number of rows per job
  766. #
  767. # Example:
  768. #
  769. # class Route < ActiveRecord::Base
  770. # include EachBatch
  771. # self.table_name = 'routes'
  772. # end
  773. #
  774. # bulk_queue_background_migration_jobs_by_range(Route, 'ProcessRoutes')
  775. #
  776. # Where the model_class includes EachBatch, and the background migration exists:
  777. #
  778. # class Gitlab::BackgroundMigration::ProcessRoutes
  779. # def perform(start_id, end_id)
  780. # # do something
  781. # end
  782. # end
  783. def bulk_queue_background_migration_jobs_by_range(model_class, job_class_name, batch_size: BACKGROUND_MIGRATION_BATCH_SIZE)
  784. raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?('id')
  785. jobs = []
  786. model_class.each_batch(of: batch_size) do |relation|
  787. start_id, end_id = relation.pluck('MIN(id), MAX(id)').first
  788. if jobs.length >= BACKGROUND_MIGRATION_JOB_BUFFER_SIZE
  789. # Note: This code path generally only helps with many millions of rows
  790. # We push multiple jobs at a time to reduce the time spent in
  791. # Sidekiq/Redis operations. We're using this buffer based approach so we
  792. # don't need to run additional queries for every range.
  793. BackgroundMigrationWorker.perform_bulk(jobs)
  794. jobs.clear
  795. end
  796. jobs << [job_class_name, [start_id, end_id]]
  797. end
  798. BackgroundMigrationWorker.perform_bulk(jobs) unless jobs.empty?
  799. end
  800. # Queues background migration jobs for an entire table, batched by ID range.
  801. # Each job is scheduled with a `delay_interval` in between.
  802. # If you use a small interval, then some jobs may run at the same time.
  803. #
  804. # model_class - The table being iterated over
  805. # job_class_name - The background migration job class as a string
  806. # delay_interval - The duration between each job's scheduled time (must respond to `to_f`)
  807. # batch_size - The maximum number of rows per job
  808. #
  809. # Example:
  810. #
  811. # class Route < ActiveRecord::Base
  812. # include EachBatch
  813. # self.table_name = 'routes'
  814. # end
  815. #
  816. # queue_background_migration_jobs_by_range_at_intervals(Route, 'ProcessRoutes', 1.minute)
  817. #
  818. # Where the model_class includes EachBatch, and the background migration exists:
  819. #
  820. # class Gitlab::BackgroundMigration::ProcessRoutes
  821. # def perform(start_id, end_id)
  822. # # do something
  823. # end
  824. # end
  825. def queue_background_migration_jobs_by_range_at_intervals(model_class, job_class_name, delay_interval, batch_size: BACKGROUND_MIGRATION_BATCH_SIZE)
  826. raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?('id')
  827. model_class.each_batch(of: batch_size) do |relation, index|
  828. start_id, end_id = relation.pluck('MIN(id), MAX(id)').first
  829. # `BackgroundMigrationWorker.bulk_perform_in` schedules all jobs for
  830. # the same time, which is not helpful in most cases where we wish to
  831. # spread the work over time.
  832. BackgroundMigrationWorker.perform_in(delay_interval * index, job_class_name, [start_id, end_id])
  833. end
  834. end
  835. end
  836. end
  837. # rubocop:enable all