简体   繁体   中英

Rails & PSQL: how to convert a column of type STRING to UUID with a fallback value

I'm using an extension called 'pgcrypto' to add a support for UUIDs.

Currently I have a column called creator_id of type string but I want to change its type to UUID.

At first I tried:

change_column :communities, :creator_id, :uuid

And I got this:

PG::DatatypeMismatch: ERROR:  column "creator_id" cannot be cast automatically to type uuid
HINT:  You might need to specify "USING creator_id::uuid".

So I tried:

change_column :communities, :creator_id, "uuid USING creator_id::uuid"

The problem is, during early stages of development it was filled with placeholder values that don't even look like a UUID, so I'm getting the following error:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type uuid

So I want to fallback to some default UUID when such an exception is raised. How do I achieve that?

First, create a migration with uuid-ossp and pgcrypto

class EnableUuidExtension < ActiveRecord::Migration[5.2]
      def change
        enable_extension 'uuid-ossp'
        enable_extension 'pgcrypto'
      end
    end

Then, create another migration to convert id into uuid . For instance,

class ChangeIdToUuidInUser < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :uuid, :uuid, default: 'uuid_generate_v4()', null: false
    change_table :users do |t|
      t.remove :id
      t.rename :uuid, :id
    end
    execute 'ALTER TABLE users ADD PRIMARY KEY (id);'
  end
end

After then open postgres database with this command psql -U username databaseName You will enter in postgres shell, run following command

=# CREATE EXTENSION pgcrypto;
=# \q

Finally, run rails db:migrate

This is what I ended up doing:

class UpdateCreatorIdInCommunities < ActiveRecord::Migration[5.1]
    def up
        execute "CREATE OR REPLACE FUNCTION string_to_uuid(text, uuid) RETURNS uuid AS $$
        BEGIN
          RETURN $1::uuid;
        EXCEPTION
          WHEN invalid_text_representation THEN
            RETURN $2;
        END;
        $$ language plpgsql immutable;"
        last_user_created = User.order(:created_at).last
        user_id = last_user_created ? quote(last_user_created.id) : "NULL"
        change_column :communities, :creator_id, "uuid USING string_to_uuid(\"creator_id\", #{user_id})"
    end

    def down
        change_column :communities, :creator_id, :string
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM