我认为你是对的,你必须拔出旧对并将新对(使用重命名的密钥)放回。
你可以用单线做到这一点:
(h - from_key) || hstore(to_key, h -> from_key)
h 是 hstore,from_key 是您要更改的键,to_key 是您要更改的键。这将返回一个具有所需更改的新 hstore,但它假定 from_key 在 h 中;如果from_key 不在h 中,那么你最终会在你的hstore 中得到to_key -> NULL。如果您和所有理智的人一样,不想要杂散的 NULL,那么我会将逻辑包装在一个简单的函数中,以便更容易添加存在检查;像这样:
create or replace function
change_hstore_key(h hstore, from_key text, to_key text) returns hstore as $$
begin
if h ? from_key then
return (h - from_key) || hstore(to_key, h -> from_key);
end if;
return h;
end
$$ language plpgsql;
那么你可以把这两个都说出来,得到预期的结果:
=> select change_hstore_key('a=>1,b=>2,c=>3'::hstore, 'b', 'pancakes');
change_hstore_key
------------------------------
"pancakes"=>"2", "a"=>"1", "c"=>"3"
=> select change_hstore_key('a=>1,b=>2,c=>3'::hstore, 'pancakes', 'X');
change_hstore_key
------------------------------
"a"=>"1", "b"=>"2", "c"=>"3"