Previous: pg_stmt Table of contents Next: pg_excpt

The pg_bytea class

This is the class to use for reading and writing data that is typed as bytea (binary), in conjunction with pg_stream.

Public functions

pg_bytea()
Default constructor. Initializes the object to a null value.
pg_bytea(void* ptr, unsigned int len)
Constructor. ptr should point to binary data on the host that needs to be passed to the server through a pg_stream object. len is the size of the binary data pointed to by ptr, see the set_src_data() function for more information.
~pg_bytea()
Destructor. If a buffer had been allocated for storing binary data coming from the server, it gets freed here.
void set_src_data(void* ptr, unsigned int len)
Set the source pointer and size of the binary data in order to pass it to a pg_stream with the operator<<(pg_bytea&) function.
Note that the data is not copied by the pg_bytea object, thus it shouldn't be freed before the pg_bytea object has actually used it.
bool is_null() const
Returns true if the bytea result fetched into the object is null. This is true either when a fetch has returned NULL or when the object has just been initialized without assigning a data pointer to it.
void* get_data_ptr() const
Returns a pointer to the binary data (also a NULL pointer if the is_null() function returns true). That pointer may have been set by a previous call to set_src_data(), or by a fetch of bytea contents from the database with the pg_stream::operator>>(pg_bytea&) function.
unsigned int get_data_size() const
Returns the size of the binary data, either set by a call to set_src_data() or got from the server after a fetch.

Example

The sample function below puts the contents of a buffer into a bytea column (assumes a table btest(k int, b bytea)):
void insert_bytea(db_cnx& cnx, const char* buf, unsigned int size)
{
  pg_stream s("INSERT INTO btest(k,b) VALUES(:key, :bindata)", cnx);
  pg_bytea b(buf, size);
  s << 1 << b;
}
That other function reads the bytea column, puts the contents into an opened file, and then nulls the bytea field in the table.
void consume_bytea(db_cnx& cnx, int key, FILE *f)
{
  pg_stream s("SELECT b FROM btest WHERE k=:pk");
  s << key;
  if (!s.eos()) {
   pg_bytea b;
   s >> b;
   fwrite(b.get_data_ptr(), b.get_data_size(), 1, f);
   pg_bytea nullb;
   pg_stream s2("UPDATE btest SET b=:nb WHERE k=:pk", cnx);
   s2 << nullb << key;
  }
}

Efficiency tips

The most efficient way to pass binary data through a pg_stream to the server is by using bind variables (instead of inline parameters). In this case the binary data doesn't get internally converted into an ASCII representation, thus reducing time and space used. See the pg_stream::use_bind_variables() function.

Currently, the pgstream internals always retrieve query results as text data, so that reading a bytea field always involves a text-to-binary conversion step.


Previous: pg_stmt Table of contents Next: pg_excpt