# frozen_string_literal: true

class DropVulnerabilityOccurrencePipelines < Gitlab::Database::Migration[2.2]
  include Gitlab::Database::SchemaHelpers

  TABLE_NAME = :vulnerability_occurrence_pipelines
  TRIGGER_NAME = 'trigger_8ba31bddd655'

  milestone '17.6'

  disable_ddl_transaction!

  def up
    drop_table TABLE_NAME
    drop_function TRIGGER_NAME
  end

  def down
    create_table TABLE_NAME do |t|
      t.timestamps_with_timezone null: false
      t.bigint :occurrence_id, null: false
      t.bigint :pipeline_id, null: false
      t.bigint :project_id
    end

    add_concurrent_index TABLE_NAME, [:occurrence_id, :pipeline_id],
      unique: true,
      name: 'vulnerability_occurrence_pipelines_on_unique_keys'
    add_concurrent_index TABLE_NAME, [:occurrence_id, :id],
      order: { occurrence_id: :asc, id: :desc },
      name: 'index_vulnerability_occurrence_pipelines_occurrence_id_and_id'
    add_concurrent_index TABLE_NAME, :pipeline_id,
      name: 'index_vulnerability_occurrence_pipelines_on_pipeline_id'

    add_concurrent_foreign_key TABLE_NAME, :vulnerability_occurrences,
      column: :occurrence_id, on_delete: :cascade, name: 'fk_rails_dc3ae04693'

    install_sharding_key_assignment_trigger(
      table: TABLE_NAME,
      sharding_key: :project_id,
      parent_table: :vulnerability_occurrences,
      parent_sharding_key: :project_id,
      foreign_key: :occurrence_id,
      trigger_name: TRIGGER_NAME
    )
  end
end
