Skip to content

Instantly share code, notes, and snippets.

@cooljl31
Forked from estum/migrate_hstore_to_json.rb
Created October 11, 2022 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cooljl31/e36689fa14f42470b2747f07f7d68695 to your computer and use it in GitHub Desktop.
Save cooljl31/e36689fa14f42470b2747f07f7d68695 to your computer and use it in GitHub Desktop.
Ruby on Rails & Postgres: Reversible migrate hstore column to jsonb with contents
class MigrateHstoreToJson < ActiveRecord::Migration
def up
rename_column :posts, :data, :data_hstore
add_column :posts, :data, :jsonb, default: {}, null: false, index: { using: 'gin' }
execute 'UPDATE "posts" SET "data" = json_object(hstore_to_matrix("data_hstore"))::jsonb'
remove_column :posts, :data_hstore
end
def down
rename_column :posts, :data, :data_jsonb
add_column :posts, :data, :hstore, default: {}, null: false
execute 'UPDATE "posts" SET "data" = (SELECT hstore(key, value) FROM jsonb_each_text("data_jsonb"))'
remove_column :posts, :data_jsonb
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment