SET search_path=revision,public;

ALTER TYPE branch_type_type RENAME TO old_branch_type_type;
ALTER TABLE branch RENAME COLUMN type TO old_type;

CREATE TYPE branch_type_type AS ENUM ('trunk','approved','stable','archive','deleted');
ALTER TABLE branch ADD COLUMN type branch_type_type NOT NULL DEFAULT 'stable';
UPDATE branch SET type=old_type::text::branch_type_type;

ALTER TABLE branch DROP COLUMN old_type;
DROP TYPE old_branch_type_type;

ALTER TABLE branch ADD CONSTRAINT valid_trunk
    CHECK ((type='trunk' AND id=0 AND created_by=0) OR (type<>'trunk' AND id>0 AND created_by>0));
ALTER TABLE branch ADD CONSTRAINT valid_finished
    CHECK ((type IN ('trunk','stable','approved') AND finished_by=0) OR (type IN ('archive','deleted') AND finished_by>0));
ALTER TABLE branch ADD CONSTRAINT valid_deleted
    CHECK (type<>'deleted' OR state='unavailable');

SET search_path=public;
