Upgrade PostgreSQL JSON column to JSONB?

前端 未结 2 1472
[愿得一人]
[愿得一人] 2020-12-09 07:24

After upgrading to PostgreSQL 9.4, how do I convert all my JSON columns into JSONB columns?

I don\'t mind losing any duplicate keys and whitespace.

相关标签:
2条回答
  • 2020-12-09 08:06
    ALTER TABLE t ALTER COLUMN j TYPE jsonb USING j::text::jsonb;
    
    0 讨论(0)
  • 2020-12-09 08:24

    In the context of Rails, here is an ActiveRecord migration alternative:

    def change
      reversible do |dir|
        dir.up { change_column :models, :attribute, 'jsonb USING CAST(attribute AS jsonb)' }
        dir.down { change_column :models, :attribute, 'json USING CAST(attribute AS json)' }
      end
    end
    

    I tested this on a table with 120 000 records, each record having four json columns and it took me about a minute to migrate that table. Of course, it depends on how complex the json structure is.

    Also, notice that if your existing records have a default value of {}, you have to add to the above statements default: {}, because otherwise you'll have jsonb columns, but the default value will remain as '{}'::json.

    0 讨论(0)
提交回复
热议问题