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

后端 未结 2 512
情书的邮戳
情书的邮戳 2021-01-17 21:08

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 j

2条回答
  •  醉酒成梦
    2021-01-17 21:40

    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 
    #include 
    #include 
    #include 
    
    // ... 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.

提交回复
热议问题