Skip to content

Instantly share code, notes, and snippets.

@crashbell
Forked from d11wtq/enum.sql
Created August 7, 2017 07:08
Show Gist options
  • Save crashbell/c7767d583d239ea0a63b1e61d0f5cbf9 to your computer and use it in GitHub Desktop.
Save crashbell/c7767d583d239ea0a63b1e61d0f5cbf9 to your computer and use it in GitHub Desktop.

Revisions

  1. @d11wtq d11wtq created this gist Oct 26, 2012.
    25 changes: 25 additions & 0 deletions enum.sql
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    /*
    Assuming you have an enum type like this.
    You want to rename 'pending' to 'lodged'
    */
    CREATE TYPE dispute_status AS ENUM('pending', 'resolved', 'open', 'cancelled');

    BEGIN;

    ALTER TYPE dispute_status ADD VALUE 'lodged';
    UPDATE dispute SET status = 'lodged' WHERE status = 'pending';

    /* if it was a default value on the column, also do this */
    ALTER TABLE disputes ALTER COLUMN status SET DEFAULT 'lodged';

    /* Make a new temporary type with the enum you want */
    CREATE TYPE dispute_status_new AS ENUM('lodged', 'resolved', 'open', 'cancelled');

    /* Migrate to the new type, specifying the cast to a string */
    ALTER TABLE disputes ALTER COLUMN status SET DATA TYPE dispute_status_new USING status::text;

    /* Switch the types over */
    DROP TYPE dispute_status;
    ALTER TYPE dispute_status_new RENAME TO dispute_status;

    COMMIT;