在PostgreSQL 9.2中重命名hstore密钥

Jef*_*eff 10 postgresql hstore

我一直在评估PostgreSQL的hstore功能(9.2),而精细手册中唯一没有明确指出的是如何重命名密钥.例如,我怎样才能将密钥重命名cai_count

"c"=>"3", "ai_voltage"=>"3", "ai_temperature"=>"28"

我认为没有直接的方法可以做到这一点,它涉及将c密钥复制到ai_count密钥,然后丢弃c密钥.我怎么能这样做,理想情况下作为一个可以应用于多个记录的单行程?

mu *_*ort 12

我认为你是对的,你必须拉出旧的一对,并把新的对(重命名的密钥)放回去.

你可以用一个班轮做到这一点:

(h - from_key) || hstore(to_key, h -> from_key)
Run Code Online (Sandbox Code Playgroud)

这里h是hstore,from_key是要更改钥匙,to_key是你想改变它到什么.这将返回一个具有所需更改的新hstore,但它假定它from_keyh; 如果from_key不是,h那么你最终会to_key -> NULL在你的hstore中找到一个.如果你像所有理智的人一样,不想要迷路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;
Run Code Online (Sandbox Code Playgroud)

然后你可以说这两个并得到预期的结果:

=> 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"
Run Code Online (Sandbox Code Playgroud)