It took me a few days (after following the cdbi mail-list for months) to wrap my head around how to do this, but after much gnashing of teeth, here's a nice snippet to add to your Class::DBI base classes. It irked me that there wasn't a builtin way to do this - at least not without loading every maching record into memory just to get a count. If I'm wrong on that count, please enlighten.
Code shamelessly adapted from Class::DBI::AbstractSearch - many thanks to Tatsuhiko Miyagawa for that simple but ever so useful module. My next challenge is to learn how to make a mixin/plugin for Class::DBI out of this. (Any suggestions?)
package MusicDBI; use base 'Class::DBI'; use SQL::Abstract; __PACKAGE__->set_sql( count_where => 'SELECT COUNT(*) FROM __TABLE__ %s' ); sub count_where { my $class = shift; my $where = (ref $_[0]) ? $_[0] : { @_ }; my $attr = (ref $_[0]) ? $_[1] : undef; my $order = ($attr) ? delete($attr->{order_by}) : undef; $class->can('sql_count_where') or do { require Carp; Carp::croak("$class should set_sql(count_where => ...)"); }; my $sql = SQL::Abstract->new(%$attr); my($phrase, @bind) = $sql->where($where, $order); my $count = $class->sql_count_where($phrase)->select_val(@bind); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Class::DBI count_where method
by dragonchild (Archbishop) on May 19, 2004 at 17:56 UTC | |
by dcvr69 (Beadle) on May 19, 2004 at 18:20 UTC | |
by salvadors (Pilgrim) on May 25, 2004 at 07:16 UTC |