Skip to content

Instantly share code, notes, and snippets.

@clarkbw
Last active February 10, 2022 17:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarkbw/cdd6c46de6c9c048aa69345784a97d7b to your computer and use it in GitHub Desktop.
Save clarkbw/cdd6c46de6c9c048aa69345784a97d7b to your computer and use it in GitHub Desktop.
A rails migration for creating and reverting a hypertable
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