Type conversion. What do I do with a PostgreSQL OID value in libpq in C?

主宰稳场 提交于 2019-12-01 15:54:34

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
  }
}

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.

To get the type name from an OID, just cast it to regtype:

SELECT  700::oid::regtype -- real

To get the type of any columns (or variable in plpgsql), use pg_typeof():

SELECT  pg_typeof(1::real) -- real

Gives you an answer of type regtype which is displayed as text in psql or pgAdmin. You can cast it to text explicitly if needed:

SELECT  pg_typeof(1::real)::text -- real

There is also this "big list", vulgo catalog table pg_type, where types are registered. This can be big, have a peek:

SELECT * from pg_type LIMIT 10;

More info in the excellent manual.

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