LoginSignup
1
2

More than 3 years have passed since last update.

Rails で PostgreSQL のパーティションを利用したい

Last updated at Posted at 2020-04-21

なにこれ?

Ruby on Rails で PostgreSQL のハッシュパーティションを使いたいよねー、という方!こうすればできました。たぶん、rails db:migrate or db:rollback したら DDL が発行されてよしなに設定されるはず。

サンプルコード

class CreateStaffs < ActiveRecord::Migration[6.0]
  def change
    reversible do |dir|
      dir.up do
        execute <<~"SQL"
                    CREATE TABLE staffs (id uuid PRIMARY KEY UNIQUE, email varchar NOT NULL, cname varchar NOT NULL, created_at timestamp(6) NOT NULL, updated_at timestamp(6) NOT NULL) PARTITION BY HASH (id);
                    #{(0..99).map{|num| "CREATE TABLE staffs_partition_#{num} PARTITION OF staffs FOR VALUES WITH(MODULUS 100,REMAINDER #{num});"}.join}
        SQL
      end
      dir.down do
        execute <<-SQL
                   DROP TABLE staffs;
        SQL
      end
    end
  end
end

おわりに

PostgreSQL 11 からの機能なので、使えない環境の方もいらっしゃると思われます。が、あとで楽できそうなので必要に応じてパーテイションを作っておくことが良さそうですね。

1
2
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
2