数据迁移脚本实现判断索引是否存在 并执行命令

2020-07-01  本文已影响0人  __默默无闻

在开发过程中 数据库迁移的重要性 无需赘述,总之 编写migrations 是必不可少的!

编写migrations的时候,可能会遇到特定场景,例如需要判断该索引是否存在,如果存在则删除索引,如果不存在进行下一步操作。但是在mysql中,目前不知道 if exist...,下面将介绍遇到这种问题的解决方案。

//demo使用[https://github.com/pressly/goose](https://github.com/pressly/goose)包进行migration管理
-- +goose Up   
-- +goose StatementBegin
// 判断`unique_email`索引是否存在,如果存在执行alter...,不存在执行后面的内容
select if (
    exists(
        select distinct index_name from information_schema.statistics where table_name = 'user' and index_name = 'unique_email'
    )
    ,'alter table `user-user` drop index `unique_email`'
    ,'select ''index index_1 exists'' _______;') into @a;
-- +goose StatementEnd

-- +goose StatementBegin
PREPARE stmt1 FROM @a;
-- +goose StatementEnd

-- +goose StatementBegin
EXECUTE stmt1;
-- +goose StatementEnd

-- +goose StatementBegin
DEALLOCATE PREPARE stmt1;
-- +goose StatementEnd
上一篇 下一篇

猜你喜欢

热点阅读