# typed: true
class CreatePartitionedBlobEntries < ActiveRecord::Migration[7.0]
  NUM_PARTITIONS = 64

  def up
    main_table_sql = <<~SQL.split("\n").map(&:strip).join(" ")
      CREATE TABLE blob_entries_p (
        sha256 bytea NOT NULL,
        base_sha256 bytea,
        content_type character varying NOT NULL,
        size integer NOT NULL,
        contents bytea NOT NULL,
        created_at timestamp(6) without time zone NOT NULL
      ) PARTITION BY HASH (sha256)
    SQL
    execute main_table_sql

    NUM_PARTITIONS.times do |partnum|
      partition_table_name = :"blob_entries_p_#{partnum.to_s.rjust(2, "0")}"
      partition_table_sql = <<~SQL.split("\n").map(&:strip).join(" ")
        CREATE TABLE #{partition_table_name}
        PARTITION OF blob_entries_p FOR 
        VALUES WITH (
            MODULUS #{NUM_PARTITIONS}, 
            REMAINDER #{partnum}
          )
      SQL
      execute partition_table_sql
      add_index partition_table_name, :sha256, unique: true
    end

    add_index :blob_entries_p, :sha256, unique: true
  end

  def down
    drop_table :blob_entries_p
  end
end
