Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

pg_party

> 后端框架
Open source

ActiveRecord PostgreSQL Partitioning

529 stars0 likes3 views
WebsiteGitHub

About

ActiveRecord PostgreSQL Partitioning

PgParty

ActiveRecord migrations and model helpers for creating and managing PostgreSQL 10+ partitions!

Features

  • Migration methods for partition specific database operations
  • Model methods for querying partitioned data, creating adhoc partitions, and retreiving partition metadata

Limitations

  • Partition tables are not represented correctly in db/schema.rb — please use the :sql schema format

Compatibility

This gem is tested against:

  • Rails: 7.2, 8.0, 8.1
  • Ruby: 3.2, latest (currently 3.4 at the time of this commit)
  • PostgreSQL: 14, 15, 16, 17, 18

Future Work

I plan to separate out the model functionality into a new gem and port the migration functionality into pg_ha_migrations (some of which has already been done). I will continue to maintain this gem (bugfixes / support for new versions of Rails) until that work is complete.

I originally planned to add a feature for automatic partition creation, but I think that functionality would be better served by pg_partman.

Installation

Add this line to your application's Gemfile:

ruby
gem 'pg_party'

And then execute:

$ bundle

Or install it yourself as:

$ gem install pg_party

Note that the gemspec does not require pg, as some model methods may work for other databases. Migration methods will be unavailable unless pg is installed.

Configuration

These values can be accessed and set via PgParty.config and PgParty.configure.

  • caching
    • Whether to cache currently attached partitions and anonymous model classes
    • Default: true
  • caching_ttl
    • Length of time (in seconds) that cache entries are considered valid
    • Default: -1 (never expire cache entries)
  • schema_exclude_partitions
    • Whether to exclude child partitions in rake db:structure:dump
    • Default: true
  • create_template_tables
    • Whether to create template tables by default. Use the template: option when creating partitioned tables to override this default.
    • Default: true
  • create_with_primary_key
    • Whether to add primary key constraints to partitioned (parent) tables by default.
      • This behavior is disabled by default as this configuration usually requires composite primary keys to be specified and ActiveRecord does not natively support composite primary keys. There are workarounds such as the composite_primary_keys gem.
      • This is not supported for Postgres 10 (requires Postgres 11+)
      • Primary key constraints must include all partition keys, for example: primary_key: [:id, :created_at], partition_key: :created_at
      • Partition keys cannot use expressions
      • Can be overridden via the create_with_primary_key: option when creating partitioned tables
    • Default: false
  • include_subpartitions_in_partition_list
    • Whether to include nested subpartitions in the result of YourModelClass.partiton_list mby default. You can always pass the include_subpartitions: option to override this.
    • Default: false (for backward compatibility)

Note that caching is done in-memory for each process of an application. Attaching / detaching partitions will clear the cache, but only for the process that initiated the request. For multi-process web servers, it is recommended to use a TTL or disable caching entirely.

Example

ruby
# in a Rails initializer
PgParty.configure do |c|
  c.caching_ttl = 60
  c.schema_exclude_partitions = false
  c.include_subpartitions_in_partition_list = true
  # Postgres 11+ users starting fresh may consider the below options to rely on Postgres' native features instead of
  # this gem's template tables feature.
  c.create_template_tables = false
  c.create_with_primary_key = true
end

Usage

Migrations

Methods

These methods are available in migrations as well as ActiveRecord::Base#connection objects.

  • create_range_partition
    • Create partitioned table using the range partitioning method
    • Required args: table_name, partitition_key:
  • create_list_partition
    • Create partitioned table using the list partitioning method
    • Required args: table_name, partition_key:
  • create_hash_partition (Postgres 11+)
    • Create partitioned table using the hash partitioning method
    • Required args: table_name, partition_key:
  • create_range_partition_of
    • Create partition in range partitioned table with partition key between range of values
    • Required args: table_name, start_range:, end_range:
    • Create a subpartition by specifying a partition_type: of :range, :list, or :hash and a partition_key:
  • create_list_partition_of
    • Create partition in list partitioned table with partition key in list of values
    • Required args: table_name, values:
    • Create a subpartition by specifying a partition_type: of :range, :list, or :hash and a partition_key:
  • create_hash_partition_of (Postgres 11+)
    • Create partition in hash partitioned table for partition keys with hashed values having a specific remainder
    • Required args: table_name, modulus:, remainder
    • Create a subpartition by specifying a partition_type: of :range, :list, or :hash and a partition_key:
    • Note that all partitions in a hash partitioned table should have the same modulus. See Examples for more info.
  • create_default_partition_of (Postgres 11+)
    • Create a default partition for values not falling in the range or list constraints of any other partitions
    • Required args: table_name
  • attach_range_partition
    • Attach existing table to range partitioned table with partition key between range of values
    • Required args: parent_table_name, child_table_name, start_range:, end_range:
  • attach_list_partition
    • Attach existing table to list partitioned table with partition key in list of values
    • Required args: parent_table_name, child_table_name, values:
  • attach_hash_partition (Postgres 11+)
    • Attach existing table to hash partitioned table with partition key hashed values having a specific remainder
    • Required args: parent_table_name, child_table_name, modulus:, remainder
  • attach_default_partition (Postgres 11+)
    • Attach existing table as the default partition
    • Required args: parent_table_name, child_table_name
  • detach_partition
    • Detach partition from both range and list partitioned tables
    • Required args: parent_table_name, child_table_name
  • create_table_like
    • Clone any existing table
    • Required args: table_name, new_table_name
  • partitions_for_table_name
    • List all attached partitions for a given table
    • Required args: table_name, include_subpartitions: (true or false)
  • parent_for_table_name
    • Fetch the parent table for a partition
    • Required args: table_name
    • Pass optional traverse: true to return the top-level table in the hierarchy (for subpartitions)
    • Returns nil if the table is not a partition / has no parent
  • table_partitioned?
    • Returns true if the table is partitioned (false for non-partitioned tables and partitions themselves)
    • Required args: table_name
  • add_index_on_all_partitions
    • Recursively add an index to all partitions and subpartitions of table_name using Postgres's ADD INDEX CONCURRENTLY algorithm which adds the index in a non-blocking manner.
    • Required args: table_name, column_name (all add_index arguments are supported)
    • Use the in_threads: option to add indexes in parallel threads when there are many partitions. A value of 2 to 4 may be reasonable for tables with many large partitions and hosts with 4+ CPUs/cores.
    • Use disable_ddl_transaction! in your migration to disable transactions when using this command with in_threads: or algorithm: :concurrently.

Examples

Create range partitioned table on created_at::date with two partitions:

ruby
class CreateSomeRangeRecord { "(created_at::date)" } do |t|
      t.text :some_value
      t.timestamps
    end

    # optional name argument is used to specify child table name
    create_range_partition_of \
      :some_range_records,
      name: :some_range_records_a,
      start_range: "2019-06-07",
      end_range: "2019-06-08"

    # optional name argument is used to specify child table name
     create_range_partition_of \
       :some_range_records,
       name: :some_range_records_b,
       start_range: "2019-06-08",
       end_range: "2019-06-09"
  end
end

Create list partitioned table on id with two partitions:

ruby
class CreateSomeListRecord "
    create_list_partition_of \
      :some_list_records,
      values: 1..100

    # without name argument, child partition created as "some_list_records_"
     create_list_partition_of \
       :some_list_records,
       values: 101..200

    # default partition support is available in Postgres 11 or higher
     create_default_partition_of \
       :some_list_records
  end
end

Create hash partitioned table on account_id with two partitions (Postgres 11+ required):

  • A hash partition can be used to spread keys evenly(ish) across partitions
  • modulus: should always equal the total number of partitions planned for the table
  • remainder: is an integer which should be in the range of 0 to modulus-1
ruby
class CreateSomeHashRecord "
    create_hash_partition_of \
      :some_hash_records,
      modulus: 2,
      remainder: 0

    # without name argument, child partition created as "some_list_records_"
    create_hash_partition_of \
      :some_hash_records,
      modulus: 2,
      remainder: 1
  end
end

Advanced example with subpartitioning: Create list partitioned table on account_id subpartitioned by range on created_at with default partitions. This example is for a table with no primary key... perhaps for some analytics use case.

  • Default partitions are only supported in Postgres 11+
…

Template Tables

Unfortunately, PostgreSQL 10 doesn't support indexes on partitioned tables. However, individual partitions can have indexes. To avoid explicit index creation for every new partition, we've introduced the idea of template tables. For every call to create_list_partition and create_range_partition, a clone _template is created. Indexes, constraints, etc. created on the template table will propagate to new partitions in calls to create_list_partition_of and create_range_partition_of:

  • Subpartitions will correctly clone from template tables if a template table exists for the top-level ancestor
  • When using Postgres 11 or higher, you may wish to disable template tables and use the native features instead, see Configuration
    but this may result in you using composite primary keys, which is not natively supported by ActiveRecord.
…

Attaching Existing Tables as Partitions

Attach an existing table to a range partitioned table:

ruby
class AttachRangePartition < ActiveRecord::Migration[5.1]
  def up
    attach_range_partition \
      :some_range_records,
      :some_existing_table,
      start_range: "2019-06-09",
      end_range: "2019-06-10"
  end
end

Attach an existing table to a list partitioned table:

ruby
class AttachListPartition < ActiveRecord::Migration[5.1]
  def up

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecordpartitionpartitioningpostgres

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架