POSTGRES:将主键类型从varchar更改为uuid,并由其他tabless引用

时间:2015-10-30 17:14:22

标签: postgresql

我有表客户和用户,我想将他们的ID从字符变为uuid。

# Job that takes a variable amount of time
$Job = Start-Job -ScriptBlock { 
    Start-Sleep -Seconds $(5..15 | Get-Random)
    return "I woke up!"
}

# Wait for 10 seconds
if(Wait-Job $Job -Timeout 10){
    # Job returned before timeout, let's grab results
    $Results = $Job | Receive-Job 
} else {
    # Job did not return in time
    # You can log, do error handling, defer to a default value etc. in here
}

# Clean up
Get-Job | Remove-Job

我试过了:

=>\d customers;
         Table "public.customers"
  Column  |       Type        | Modifiers
----------+-------------------+-----------
 id       | character varying | not null
 name     | character varying | not null
Indexes:
    "customers_pkey" PRIMARY KEY, btree (id)
    "customers_name_key" UNIQUE CONSTRAINT, btree (name)
Referenced by:
    TABLE "users" CONSTRAINT "users_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id) DEFERRABLE INITIALLY DEFERRED

=>\d users;
             Table "public.users"
    Column     |       Type        | Modifiers
---------------+-------------------+-----------
 id            | character varying | not null
 name          | character varying | not null
 customer_id   | character varying | not null
 login         | character varying | not null
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
    "users_login_key" UNIQUE CONSTRAINT, btree (login)
Foreign-key constraints:
    "users_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id) DEFERRABLE INITIALLY DEFERRED

但是在这行之后我遇到了不兼容的类型错误

=>begin;
set constraints all deferred;
ALTER TABLE users alter customer_id type uuid using customer_id::uuid;
ALTER TABLE customers alter id type uuid using id::uuid;
end;

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

您肯定希望删除外键约束。令您惊讶的是,您不必为PostgreSQL更改PK约束或索引来更改数据类型。我设置了一个测试,它运行良好,只需要先删除FK,然后再重新添加即可。