Skip to content

Commit

Permalink
allow to do a change_table to change partition key
Browse files Browse the repository at this point in the history
  • Loading branch information
louiseGrandjonc committed Sep 11, 2019
1 parent 573b57f commit 0030104
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
18 changes: 15 additions & 3 deletions lib/activerecord-multi-tenant/migrations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,24 @@ module ActiveRecord
module ConnectionAdapters # :nodoc:
module SchemaStatements
alias :orig_create_table :create_table
def create_table(table_name, options = {}, &block)
ret = orig_create_table(table_name, options.except(:partition_key), &block)
alias :orig_change_table :change_table

def change_primary_key(table_name, options)
if options[:partition_key] && options[:partition_key].to_s != 'id'
execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{table_name}_pkey"
execute "ALTER TABLE #{table_name} DROP CONSTRAINT IF EXISTS #{table_name}_pkey"
execute "ALTER TABLE #{table_name} ADD PRIMARY KEY(id, \"#{options[:partition_key]}\")"
end
end

def create_table(table_name, options = {}, &block)
ret = orig_create_table(table_name, options.except(:partition_key), &block)
change_primary_key(table_name, options)
ret
end

def change_table(table_name, options, &block)
ret = orig_change_table(table_name, options.except(:partition_key), &block)
change_primary_key(table_name, options)
ret
end
end
Expand Down
8 changes: 6 additions & 2 deletions spec/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
t.column :name, :string
end

create_table :project_categories, force: true, partition_key: :account_id do |t|
create_table :project_categories, force: true do |t|
t.column :name, :string
t.column :account_id, :integer
t.column :project_id, :integer
Expand All @@ -106,9 +106,13 @@
create_distributed_table :partition_key_not_model_tasks, :non_model_id
create_distributed_table :subclass_tasks, :non_model_id
create_distributed_table :uuid_records, :organization_id
create_distributed_table :project_categories, :account_id
create_distributed_table :allowed_places, :account_id
create_reference_table :categories

change_table :project_categories, partition_key: :account_id do |t|
end

create_distributed_table :project_categories, :account_id
end

class Account < ActiveRecord::Base
Expand Down

0 comments on commit 0030104

Please sign in to comment.