[odb-users] Re: Counting objects

Boris Kolpackov boris at codesynthesis.com
Thu Sep 22 08:18:50 EDT 2011


Hi Eric,

Boris Kolpackov <boris at codesynthesis.com> writes:

> Sum, Eric B <eric.b.sum at lmco.com> writes:
>
> > Also, I am encountering another issue that I was wondering about. I am
> > trying to figure out a fast way to determine how many objects are in a
> > table.  I know that in SQL, there is a count function such as "SELECT
> > COUNT(column) FROM table".  However, when I execute this command with
> > the db->execute command, I do not see a way to determine the result of
> > the count SQL function.  The only other way I can think of is to query
> > the table for all objects and then iterate through the result, counting
> > them one by one, but this I think may be too slow.
> 
> Yes, this will be very inefficient.
>  
> > Do you know a fast way to get the number of objects in a table?
> 
> I think the 'view' feature that is still in development will allow you
> to achieve this pretty easily. 

Just wanted to let you know that the 1.6.0.a2 pre-release that I just 
announced[1] adds support for views. Here is an example of how the above
can be achieved using this feature. Given the following persistent class:

#pragma db object
class person
{
  ...

  std::string first_;
  std::string last_;

  #pragma db id
  unsigned long id_;
};

We can create a view that returns the number of person objects stored
in the database:

#pragma db view object(person)
class person_count
{
  #pragma db column("count(" + person::id_ + ")")
  std::size_t count;
};

And then use it like this:

typedef odb::query<person_count> query;
typedef odb::result<person_count> result;

// Total number of objects.
//
result r1 = db.query<person_count> (); 

const person_count& c1 (*r1.begin ());
cerr << c1.count << endl;

// Number of objects with the "Doe" last name.
//
result r2 = db.query<person_count> (query::last == "Doe");

const person_count& c2 (*r2.begin ());
cerr << c2.count << endl;


[1] http://www.codesynthesis.com/pipermail/odb-users/2011-September/000304.html

Boris



More information about the odb-users mailing list