| 1 | package Teng::Plugin::Count; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use utf8; | ||
| 5 | |||
| 6 | our @EXPORT = qw/count/; | ||
| 7 | |||
| 8 | sub count { | ||
| 9 | my ($self, $table, $column, $where, $opt) = @_; | ||
| 10 | |||
| 11 | if (ref $column eq 'HASH') { | ||
| 12 | Carp::croak('Do not pass HashRef to second argument. Usage: $db->count($table[, $column[, $where[, $opt]]])'); | ||
| 13 | } | ||
| 14 | |||
| 15 | $column ||= '*'; | ||
| 16 | |||
| 17 | my ($sql, @binds) = $self->sql_builder->select($table, [\"COUNT($column)"], $where, $opt); | ||
| 18 | |||
| 19 | my ($cnt) = $self->dbh->selectrow_array($sql, {}, @binds); | ||
| 20 | return $cnt; | ||
| 21 | } | ||
| 22 | |||
| 23 | 1; | ||
| 24 | __END__ | ||
| 25 | |||
| 26 | =head1 NAME | ||
| 27 | |||
| 28 | Teng::Plugin::Count - Count rows in database. | ||
| 29 | |||
| 30 | =head1 NAME | ||
| 31 | |||
| 32 | package MyDB; | ||
| 33 | use parent qw/Teng/; | ||
| 34 | __PACKAGE__->load_plugin('Count'); | ||
| 35 | |||
| 36 | package main; | ||
| 37 | my $db = MyDB->new(...); | ||
| 38 | $db->count('user'); # => The number of rows in 'user' table. | ||
| 39 | $db->count('user', '*', {type => 2}); # => SELECT COUNT(*) FROM user WHERE type=2 | ||
| 40 | |||
| 41 | =head1 DESCRIPTION | ||
| 42 | |||
| 43 | This plugin provides shorthand for counting rows in database. | ||
| 44 | |||
| 45 | =head1 METHODS | ||
| 46 | |||
| 47 | =over 4 | ||
| 48 | |||
| 49 | =item $db->count($table[, $column[, \%where]]) : Int | ||
| 50 | |||
| 51 | I<$table> table name for counting | ||
| 52 | |||
| 53 | I<$column> Column name for C<<< COUNT(...) >>>, the default value is '*'. | ||
| 54 | |||
| 55 | I<\%where> : HashRef for creating where clause. The format is same as C<< $db->select() >>. This parameter is optional. | ||
| 56 | |||
| 57 | I<Return:> The number of rows. | ||
| 58 | |||
| 59 | =back | ||
| 60 |