ECPG selecting into char arrays

Started by Leif Jensenalmost 15 years ago2 messagesgeneral
Jump to latest
#1Leif Jensen
leif@crysberg.dk

Hi guys,

In version 8.2 of the ECPG documentation, section "31.6.3. Different types of host variables" has been added and includes the following (new) note:

'Note that you have to take care of the length for yourself. If you use this host variable as the target variable of a query which returns a string with more than 49 characters, a buffer overflow occurs.'

This raises a big question about how to handle fields of type 'text' !?

I am pretty sure that in pre-8.0 versions of PostgreSQL ECPG, the arrays were handled in a way that made sure not to write more than the space allowed (why else have the array size and type size included as parameters in the ECPG generated output call to ECPGdo(...) ?). Is this a new "feature" ?

With that note in mind, how do I select from a table field of type 'text' ?

Leif

#2Bosco Rama
postgres@boscorama.com
In reply to: Leif Jensen (#1)
Re: ECPG selecting into char arrays

Leif Jensen wrote:

With that note in mind, how do I select from a table field of type 'text' ?

If the type is text and you have no idea how long it will be have ecpg/libpq
allocate a buffer for you by using a pointer set to NULL as the variable:

exec sql char *val = NULL;

/* Use an indicator here if you allow the field to be a DB NULL */
exec sql
select text_field into :val
from table
where condition;

/* Check sqlca.sqlcode here */

/* val will now contain the address of an area allocated by ecpg
* holding the contents of the DB field. You can use it and then
* pass val to free() after you're done with it
*/
(do something with val)

/* Clean up */
free(val);

/* Live happily ever after */

HTH

Bosco.