2

In my app, I am using postgresql to return composite type values like this:

select row('a','b','c','d');

This query returns:

(a,b,c,d)

I am using more complex types, which contains arrays of other composite types etc. In my DB layer, I parse returned value and "unpack" arrays and other composites from it.

The problem?

select row(array[1,2,3,4]);

and

select row('{1,2,3,4}');

gives exactly same output:

("{1,2,3,4}")

How can I distinguish when this '{1,2,3,4}' is meant as regular string (possibly supplied by user) and when it is meant as array?

Should not be there something like escape sequence for { and } in composite field value?

P.S. I cannot use something like select * from row[1,2,3].

2 Answers 2

2

The safest way to determine column type is to query result set metadata.

I can't tell you how because you didn't specify your framework/language. In general you need to extend some result set class and resolve this disambiguity there.

Sign up to request clarification or add additional context in comments.

1 Comment

I knew about possiblity of queriing metadata of result set, but you (together with Craig Ringer) helped me to look on a problem from different view. Thank you both.
1

Since you're using anonymous records, this will be challenging. Observe:

SELECT pg_typeof( row('{1,2,3,4}') ), pg_typeof( row(array[1,2,3,4]) );

If possible use named types with CREATE TYPE instead of anonymous records (ROW() constructors) . Then you can examine the rowtypes.

CREATE TYPE r1 AS (col1 text);
CREATE TYPE r2 AS (col1 integer[]);

SELECT pg_typeof( row('{1,2,3,4}')::r1 ), pg_typeof( row(array[1,2,3,4])::r2 );

There may be more detail in the protocol-level result set metadata, as Ondrej suggests, offering ways to do this without having to use record types.

2 Comments

your SQL gives exact same result for both: record. What gives?
@mvp Exactly - you can't just use pg_typeof to determine the internal type of a record. I'll amend my answer to make that clearer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.