Pages

Dumping a ResultSet to a output stream

We can now use the Field class, combined with the couple of functions we designed for iterating on the ResultSet to implement a global "put to" operator on the output stream for the ResultSet class that would give us the columns names and all the values for each row.

To to that we have to redesign a bit our ResultSet class.

In its private section we want to add a vector of Field:

class ResultSet
{
private:
MYSQL_RES* rs_;
std::vector<Field> fields_;
// ...

In the public section we add a function to dump the fields name for the resultset:

void dumpFieldNames(std::ostream& os) const;

And we declare the global function "put to":

std::ostream& operator<<(std::ostream& out, ResultSet& rs);

We have to change the moveToThis() function, to manage the fields_ too:

void ResultSet::moveToThis(ResultSet& rhs)
{
rs_ = rhs.rs_;
fields_.assign(rhs.fields_.begin(), rhs.fields_.end());

rhs.rs_ = 0;
rhs.fields_.clear();
}

Same issue for the "real" ctor (the "dummy" one does not change):

ResultSet::ResultSet(MYSQL_RES* rs, unsigned int cols) : rs_(rs)
{
fields_.reserve(cols);
while(Field fld = mysql_fetch_field(rs_))
fields_.push_back(fld);
}

And here is the implementation for the two new functions:

void ResultSet::dumpFieldNames(std::ostream& os) const
{
std::vector<Field>::const_iterator it;
for(it = fields_.cbegin(); it != fields_.cend(); ++it)
os << *it << ' ';
os << std::endl;
}

std::ostream& operator<<(std::ostream& os, ResultSet& rs)
{
// header
rs.dumpFieldNames(os);

// all rows
rs.begin();
while(Row r = rs.getNext())
os << r;

return os;
}

No comments:

Post a Comment