Reputation: 1297
I want to change a column type in PostgreSQL. Let's say from INT to VARCHAR. The safe way to do it is the following:
new_<column>
.BEFORE INSERT/UPDATE
trigger).<column>
to old_<column>
and new_<column>
inside a single transaction and explicit LOCK <table>
statement.The question is how to create this BEFORE INSERT/UPDATE trigger? (2)
Upvotes: 1
Views: 422
Reputation: 858
Use a simple table foo for this example
CREATE TABLE foo (id int, idstr varchar);
Create a simple function to assign a valur to your new column idstr
CREATE OR REPLACE FUNCTION bluegreen ()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.idstr IS NULL THEN
NEW.idstr = NEW.id::varchar;
END IF;
IF NEW.id IS NULL THEN
NEW.id = NEW.idstr::int;
END IF;
RETURN NEW;
END;
$$;
And create a trigger on your table with the function previously created.
CREATE TRIGGER foo_trg
BEFORE INSERT OR UPDATE ON foo
FOR EACH ROW
EXECUTE PROCEDURE bluegreen();
https://www.postgresql.org/docs/current/sql-createtrigger.html for details on triggers
Upvotes: 2