7

I've a table created like:

CREATE TABLE tbl_test
(
  id        bigserial    PRIMARY KEY,
  interest  int          ARRAY[2]
);

I got PGresult* res using PQexec(conn, "SELECT * FROM tbl_test");

Now, how can I get int[] from PQgetvalue(res, 0, 1).
I don't want to depend on structs defined in array.h as they might change.

I could not find any API in Postgresql docs which can do things.
Please advise.

Regards,
Mayank

Max Alibaev
  • 681
  • 7
  • 17
Mayank
  • 5,454
  • 9
  • 37
  • 60
  • You've specified what return type you want; but please update the question to be explicit about what return *value* you want. – bignose May 15 '11 at 09:30

1 Answers1

7

PQgetvalue() returns the string representation of the field value unless you specify a binary cursor. In either case (string or binary cursor) you'll need to supply the code to manipulate the result into the form you want.

You might find some ideas in the PostgreSQL source code.

  • src/backend/utils/adt/arrayfuncs.c
  • src/include/utils/array.h.

And there's some code in contrib/intarray.

At http://doxygen.postgresql.org/, click "Files", then search for "array".

At the string level, which is what PQgetvalue() returns, it's probably easy to Google up some code that extracts integers from an comma-delimited string.

Mike Sherrill 'Cat Recall'
  • 91,602
  • 17
  • 122
  • 185
  • Looks like its not possible what I need :) – Mayank May 17 '11 at 12:19
  • Oh, it's possible. There's just not an API for it. You can write a function in C that accepts a string, like "{1,2,3}", and returns (or populates) an array of int. It's not dead simple, because you'd have to accommodate (or give up on) multi-dimensional arrays and arrays of arbitrary size. But it's possible. I knocked together some code to turn "{1,2,3}" into an array of int, and it wasn't too hard. (I learned to hate strtol(), though.) – Mike Sherrill 'Cat Recall' May 17 '11 at 13:51
  • Thanks a lot Catcall. I meant its not possible to get `int*` in return. Converting {x,y} is a different thing. Well, I'll be doing that :) – Mayank May 17 '11 at 13:53