Rails & Postgres: Migration to change_colomn gives error “cannot be cast to type timestamp without time zone”

前端 未结 2 1735
轻奢々
轻奢々 2021-02-19 20:09

A Rails migration to turn a \"deleted_at\" time column to a datetime column failed. Any ideas on how to solve this? It\'s a fresh install of Postgres if that is relevant.

<
2条回答
  •  囚心锁ツ
    2021-02-19 20:33

    You can't alter a field's type from time to timestamp ("datetime"), because the values couldn't be converted -- the database doesn't know the date.

    You can, however, drop and re-create the column:

    ALTER TABLE products DROP COLUMN deleted_at;
    ALTER TABLE products ADD COLUMN deleted_at timestamp;
    

    Or if this field was set to NOT NULL, you should instead do:

    ALTER TABLE products ADD COLUMN deleted_at timestamp NOT NULL;
    

    But if you insist on retaining fake values in this table like Sean, you can use ALTER...TYPE...USING like this:

    ALTER TABLE products ALTER COLUMN deleted_at TYPE timestamp USING
        CASE WHEN deleted_at IS NOT NULL THEN timestamp '1970-01-01 00:00:00' END;
    -- Or:
    ALTER TABLE products ALTER COLUMN deleted_at
        TYPE timestamp USING date '1970-01-01' + deleted_at;
    

提交回复
热议问题