Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ktat
Created December 4, 2011 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktat/1430680 to your computer and use it in GitHub Desktop.
Save ktat/1430680 to your computer and use it in GitHub Desktop.
Teng::Plugin::SearchBySQLAbstractMore
package Teng::Plugin::SearchBySQLAbstractMore;
use strict;
use warnings;
use utf8;
use Carp ();
use Teng::Iterator;
use Data::Page;
use SQL::Abstract::More;
our @EXPORT = qw/search_by_sql_abstract_more search_by_sql_abstract_more_with_pager/;
sub search_by_sql_abstract_more {
my ($self, $table_name, $where, $_opt) = @_;
my $table = $self->schema->get_table($table_name) or Carp::croak("'$table_name' is unknown table");
my %args;
$_opt->{from} ||= ($_opt->{-from} || $table_name);
foreach my $key (keys %$_opt) {
my $_k = $key =~m{^\-} ? $key : '-' . $key;
$args{$_k} ||= $_opt->{$key};
}
$args{-where} = $where;
my ($sql, @binds) = SQL::Abstract::More->new->select(%args);
my $sth = $self->dbh->prepare($sql) or Carp::croak $self->dbh->errstr;
$sth->execute(@binds) or Carp::croak $self->dbh->errstr;
my $itr = Teng::Iterator->new(
teng => $self,
sth => $sth,
sql => $sql,
row_class => $self->schema->get_row_class($table_name),
table_name => $table_name,
suppress_object_creation => $self->suppress_row_objects,
);
return $itr;
}
sub search_by_sql_abstract_more_with_pager {
my ($self, $table_name, $where, $_opt) = @_;
my $table = $self->schema->get_table($table_name) or Carp::croak("'$table_name' is unknown table");
for (qw/page rows/) {
Carp::croak("missing mandatory parameter: $_") unless exists $_opt->{$_};
}
my $page = delete $_opt->{page};
my $rows = delete $_opt->{rows};
my %args;
$_opt->{from} ||= ($_opt->{-from} || $table_name);
foreach my $key (keys %$_opt) {
my $_k = $key =~m{^\-} ? $key : '-' . $key;
$args{$_k} ||= $_opt->{$key};
}
$args{-where} = $where;
$args{-limit} = $rows;
$args{-offset} = $rows * ($page - 1);
my ($sql, @binds) = SQL::Abstract::More->new->select(%args);
$sql =~s{^\s*SELECT }{SELECT SQL_CALC_FOUND_ROWS }i;
my $sth = $self->dbh->prepare($sql) or Carp::croak $self->dbh->errstr;
$sth->execute(@binds) or Carp::croak $self->dbh->errstr;
my $total_entries = $self->dbh->selectrow_array(q{SELECT FOUND_ROWS()});
my $itr = Teng::Iterator->new(
teng => $self,
sth => $sth,
sql => $sql,
row_class => $self->schema->get_row_class($table_name),
table_name => $table_name,
suppress_object_creation => $self->suppress_row_objects,
);
my $pager = Data::Page->new();
$pager->entries_per_page($rows);
$pager->current_page($page);
$pager->total_entries($total_entries);
return ([$itr->all], $pager);
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment