类型转换。我该怎么做在C中的libpq PostgreSQL的OID值? [英] Type conversion. What do I do with a PostgreSQL OID value in libpq in C?
问题描述
我与PostgreSQL的C API工作,libpq的。我需要能够将值转换在的PGresult *
成的Ruby等效的数据类型。我目前只是选择所有的数据,并使用 PQgetvalue()
,这给了我一个的char *
,我可以转换成字符串红宝石。这很容易。但是否有任何的例子有人可以共享做从的char *
来,类型转换发言权, INT
,浮动
或双击
,根据 PQftype()返回的OID
?
I'm working with the PostgreSQL C API, libpq. I need to be able to convert the values in a PGresult*
into their equivalent data types in Ruby. I'm currently just selecting all the data and using PQgetvalue()
, which gives me a char*
that I can convert into a ruby String. That's easy. But are there any examples somebody can share that do a type conversion from the char*
to, say, int
, float
or double
, according to the OID returned by PQftype()
?
其实,总之我不知道如何跨preT OID和的文档似乎并没有给予任何指针。我发现此页面,但这并不能帮助了解如何使用此OID来做C API的类型转换。我猜有常量列表地方我可以做一个大的switch语句?
Actually, in short I have no idea how to interpret the OID and the documentation doesn't seem to give any pointers. I found this page, but that doesn't help understand how to use this OID to do a type conversion in the C API. I'm guessing there's a list of constants somewhere I can make a big switch statement from?
推荐答案
我找到了答案,询问此之后。基本上有一个名为目录/文件pg_type.h文件,旁边的libpq-fe.h和了postgres.h。您需要包含libpq-fe.h和了postgres.h,然后就可以访问诸如 TEXTOID
, BOOLOID $ C $的定义后,包括C>,
INT4OID
等。
I found the answer after asking this. Basically there's a file called catalog/pg_type.h, alongside libpq-fe.h and postgres.h. You need to include after including libpq-fe.h and postgres.h, then you can access the definitions like TEXTOID
, BOOLOID
, INT4OID
etc.
#include <stdio.h>
#include <postgres.h>
#include <libpq-fe.h>
#include <catalog/pg_type.h>
// ... snip ...
if (PQgetisnull(result, row, col)) {
// value is NULL, nothing more to do
} else {
char * value = PQgetvalue(result, row, col);
int length = PQgetlength(result, row, col);
switch (PQftype(result, col)) {
case INT2OID:
case INT4OID:
case INT8OID:
// process value as an integer
break;
default:
// just default to a text representation
}
}
您需要看看在pg_type.h文件里所有的OID实际上有一个广泛的名单,或者只是考什么,你回来干什么基本 SELECT'T'::布尔
类型的查询等,并建立只因为你需要支持新型开关。
You need to look at all the OIDs in pg_type.h to actually have an extensive list, or just test what you get back doing basic SELECT 't'::boolean
type queries etc and build up the switch only as you need a new type supporting.
这篇关于类型转换。我该怎么做在C中的libpq PostgreSQL的OID值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!