1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mysql の procedure(プロシージャ)で add partition

Posted at

サンプルテーブル log。主キーは id 一つ。

create table log (
    id              bigint          not null auto_increment,
    message         text            ,
    created_at      int             not null,
    primary key (id)
) engine = InnoDB;

このままだとパーティション作成できないので主キーをいじる

alter table log
    modify id bigint not null,
    drop primary key;
alter table log
    add primary key (id, created_at),
    modify id bigint not null auto_increment;

パーティションを 1つ追加しとく。

alter table log partition by range (created_at) (
    partition pmin values less than (0)
);

プロシージャを作って 3年分のパーティション追加。

drop procedure if exists add_monthly_partition;
delimiter //
create procedure add_monthly_partition(
    in table_name text,
    in date_func text,
    in years int)
begin
    select now() into @d;
    select date_add(@d, interval years year) into @last;

    while @d < @last do
        select concat(
            'alter table ', table_name,
            ' add partition (partition p',
            date_format(@d, '%Y%m'),
            ' values less than (', date_func, '(''',
            date_format(@d, '%Y-%m-01'), ''')))'
        ) into @ddl;
        select @ddl;
        prepare stmt from @ddl;
        execute stmt;
        deallocate prepare stmt;
        select date_add(@d, interval 1 month) into @d;
    end while;
end //
delimiter ;

call add_monthly_partition('log', 'unix_timestamp', 3);
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?