How to access a HSTORE column using PostgreSQL C library (libpq)?

廉价感情. 提交于 2021-01-28 02:56:42

问题


I cannot find any documentation regarding HSTORE data access using the C library. Currently I'm considering to just convert the HSTORE columns into arrays in my queries but is there a way to avoid such conversions?


回答1:


libpqtypes appears to have some support for hstore.

Another option is to avoid directly interacting with hstore in your code. You can still benefit from it in the database without dealing with its text representation on the client side. Say you want to fetch a hstore field; you just use:

SELECT t.id, k, v FROM thetable t, LATERAL each(t.hstorefield);

or on old PostgreSQL versions you can use the quirky and nonstandard set-returning-function-in-SELECT form:

SELECT t.id, each(t.hstorefield) FROM thetable t;

(but watch out if selecting multiple records from t this way, you'll get weird results wheras LATERAL will be fine).

Another option is to use hstore_to_array or hstore_to_matrix when querying, if you're comfortable dealing with PostgreSQL array representation.

To create hstore values you can use the hstore constructors that take arrays. Those arrays can in turn be created with array_agg over a VALUES clause if you don't want to deal with PostgreSQL's array representation in your code.

All this mess should go away in future, as PostgreSQL 9.4 is likely to have much better interoperation between hstore and json types, allowing you to just use the json representation when interacting with hstore.



来源:https://stackoverflow.com/questions/22537431/how-to-access-a-hstore-column-using-postgresql-c-library-libpq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!