Last active
February 10, 2022 17:19
-
-
Save clarkbw/cdd6c46de6c9c048aa69345784a97d7b to your computer and use it in GitHub Desktop.
A rails migration for creating and reverting a hypertable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActionsHypertable < ActiveRecord::Migration[7.0] | |
def change | |
@table_name = 'actions' | |
@time_column = 'created_at' | |
reversible do |dir| | |
dir.up do | |
execute <<-SQL | |
SELECT create_hypertable('#{@table_name}', '#{@time_column}', if_not_exists => TRUE, migrate_data => TRUE); | |
SQL | |
end | |
dir.down do | |
execute <<-SQL | |
CREATE TABLE pg_#{@table_name} (LIKE #{@table_name} INCLUDING ALL); -- duplicate table structure | |
INSERT INTO pg_#{@table_name} (SELECT * FROM #{@table_name}); -- copy all data | |
DROP TABLE #{@table_name}; -- drops hypertable | |
ALTER TABLE pg_#{@table_name} RENAME TO #{@table_name}; -- now a regular postgres table again | |
SQL | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment