表上存在索引,但迁移表示它仍未从数据库中删除它

时间:2019-02-02 23:26:54

标签: ruby-on-rails activerecord

在Rails 4应用程序上运行rake db:migrate之前,我确认要在SHOW CREATE TABLE语句上删除两个索引:

MariaDB [my_db]> SHOW CREATE TABLE document_events\G;
*************************** 1. row ***************************
       Table: document_events
Create Table: CREATE TABLE `document_events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) DEFAULT NULL,
  `document_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `document_type` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `index_document_events_on_event_id` (`event_id`),
  KEY `index_document_events_on_document_id` (`document_id`),
  KEY `index_document_events_on_document_type` (`document_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.00 sec)

请注意,有两个特定的索引,即KEY索引,分别称为index_document_events_on_document_id和index_document_events_on_document_type。因此,我创建了一个迁移以删除它们:

  def change
    change_table :document_events do |t|
      t.remove :document_type
      t.remove :document_id
      t.remove_index :document_type
      t.remove_index :document_id
      t.column :line_item_id, :string
      t.index :line_item_id
    end
  end

但是当我运行rake db:migrate时,出现以下错误:

 == 20190202215319 ChangeTableDocumentEvents: migrating ========================
-- change_table(:document_events)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Index name 'index_document_events_on_document_type' on table 'document_events' does not exist

然后我再次运行SHOW CREATE TABLE语句,索引消失了!

 MariaDB [my_db]> SHOW CREATE TABLE document_events\G;
*************************** 1. row ***************************
       Table: document_events
Create Table: CREATE TABLE `document_events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `index_document_events_on_event_id` (`event_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.00 sec)

为什么引发异常却仍然删除索引?这会导致迁移在删除迁移后中止。

这是唯一的解决方案吗?

  def change
    change_table :document_events do |t|
      t.remove :document_type
      t.remove :document_id
      t.column :line_item_id, :string
      t.index :line_item_id
    end

    remove_index :document_events, :document_type
    remove_index :document_events, :document_id
  end

0 个答案:

没有答案