Ответ 1
Я потратил некоторое время и, наконец, придумал рабочее решение.
Я опубликую его здесь для справок в будущем.
Решение
Прежде всего, у вас есть три таблицы (foo_table
, bar_table
, baz_table
), которые указывают на вашу таблицу users
с помощью внешних ключей (называемых user_id
во всех случаях). Вам нужно будет заменить идентификаторы, хранящиеся в этих столбцах, от id
до another_id
. Вот как вы можете это сделать:
-- We are dropping the foreign key constraint on dependant table (in other case it will prevent us from updating the values)
ALTER TABLE foo_table DROP CONSTRAINT fk_e52ffdeea76ed395;
-- Then, we're swapping values in foreign key column from id to another_id
UPDATE foo_table T SET user_id = (SELECT another_id FROM users WHERE id = T.user_id);
-- And finally we're creating new foreign key constraint pointing to the another_id instead of id
ALTER TABLE foo_table ADD CONSTRAINT fk_e52ffdeea76ed395 FOREIGN KEY (user_id) REFERENCES users (another_id) ON DELETE CASCADE;
Вам нужно будет повторить вышеуказанные запросы для каждой зависимой таблицы.
После этого все зависимые таблицы указывают на ваш новый столбец another_id
.
В итоге нам просто нужно заменить первичный ключ:
-- 1. Dropping the original primary key
ALTER TABLE users DROP CONSTRAINT users_pkey
-- 2. Renaming existing index for another_id (optional)
ALTER INDEX uniq_1483a5e93414710b RENAME TO users_pkey
-- 3. Creating new primary key using existing index for another_id
ALTER TABLE users ADD PRIMARY KEY USING INDEX users_pkey
-- 4. Creating index for old id column (optional)
CREATE UNIQUE INDEX users_id ON users (id)
-- 5. You can drop the original sequence generator if you won't need it
DROP SEQUENCE users_id_seq
Вы даже можете удалить исходный столбец id
, если хотите.
Я надеюсь, что это поможет кому-то.