Skip to content

Commit cfb96d6

Browse files
authored
Merge pull request #14 from code0-tech/allow-non-serial-pk-on-partitioned-tables
Allow non-serial primary key on partitioned tables
2 parents d51858c + 8487a97 commit cfb96d6

2 files changed

Lines changed: 9 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,10 @@ config.zero_track.db_partitioning.base_ar_class = 'ActiveRecord::Base' # default
8787
Include the migration helpers by inheriting from `Code0::ZeroTrack::Database::Migration[1.0]` (or the
8888
appropriate version). The following methods become available:
8989

90-
`create_partition_by_date_table(table_name, partition_column:, **options, &block)` creates a table
91-
partitioned by range on the given column. It automatically sets up a composite primary key
92-
of `(id, partition_column)`.
90+
`create_partition_by_date_table(table_name, partition_column:, primary_key: nil, **options, &block)` creates a table
91+
partitioned by range on the given column. By default, it adds a `bigserial` id column and sets up a composite
92+
primary key of `(id, partition_column)`. If `primary_key` is provided (e.g. `primary_key: %i[date other_column]`),
93+
the id column is omitted and the given columns are used as the primary key instead.
9394

9495
`create_dynamic_partition_schema` / `drop_dynamic_partition_schema` creates or drops the schema
9596
used for storing dynamic partitions.

‎lib/code0/zero_track/database/migration_helpers/table_partitioning.rb‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,23 @@ module ZeroTrack
55
module Database
66
module MigrationHelpers
77
module TablePartitioning
8-
def create_partition_by_date_table(table_name, partition_column:, **options, &block)
8+
def create_partition_by_date_table(table_name, partition_column:, primary_key: nil, **options, &block)
99
options[:options] = "PARTITION BY RANGE (#{quote_column_name(partition_column)})"
1010
options[:id] = false
1111

1212
create_table(table_name, **options) do |t|
13-
t.bigserial :id, null: false
13+
t.bigserial :id, null: false unless primary_key
1414

1515
block.call(t)
1616
end
1717

18+
pk_columns = primary_key || [:id, partition_column]
19+
1820
reversible do |dir|
1921
dir.up do
2022
execute <<~SQL.squish
2123
ALTER TABLE #{quote_table_name(table_name)}
22-
ADD PRIMARY KEY (#{quote_column_name(:id)}, #{quote_column_name(partition_column)})
24+
ADD PRIMARY KEY (#{pk_columns.map { |c| quote_column_name(c) }.join(', ')})
2325
SQL
2426
end
2527
end

0 commit comments

Comments
 (0)