Implement limited query

This commit is contained in:
swag 2021-12-22 22:23:10 -05:00
parent 8ad6b5ec2f
commit fbd569a3c2
2 changed files with 36 additions and 25 deletions

View File

@ -43,13 +43,12 @@ under sub ($c) {
}; };
get '/' => sub ($c) { get '/' => sub ($c) {
my $posts = $c->message->get_posts();
my $last_page = $c->message->get_last_page(@$posts);
my $this_page = $c->param('page') || 1; my $this_page = $c->param('page') || 1;
my @view_posts = $c->message->view_posts($this_page, $last_page, @$posts); my $last_page = $c->message->get_last_page();
my $view_posts = $c->message->get_posts($this_page);
$c->stash( $c->stash(
view_posts => \@view_posts, view_posts => $view_posts,
this_page => $this_page, this_page => $this_page,
last_page => $last_page last_page => $last_page
); );

View File

@ -13,7 +13,21 @@ sub new($class, $pg, $pg_object) {
} }
} }
sub get_posts($self) { sub get_posts($self, $this_page = undef) {
if ($this_page) {
my $row_count = $self->{'max_posts'};
my $offset = ($this_page - 1) * $row_count;
$self->pg->db->query(<<~'END_SQL', $row_count, $offset)->arrays();
SELECT to_char(message_date, 'Dy Mon DD HH:MI:SS AM TZ YYYY'),
visitor_name,
message
FROM messages
ORDER BY message_date DESC
LIMIT ? OFFSET ?;
END_SQL
}
else {
$self->pg->db->query(<<~'END_SQL')->arrays() $self->pg->db->query(<<~'END_SQL')->arrays()
SELECT to_char(message_date, 'Dy Mon DD HH:MI:SS AM TZ YYYY'), SELECT to_char(message_date, 'Dy Mon DD HH:MI:SS AM TZ YYYY'),
visitor_name, visitor_name,
@ -22,6 +36,7 @@ sub get_posts($self) {
ORDER BY message_date DESC; ORDER BY message_date DESC;
END_SQL END_SQL
} }
}
sub create_post($self, $name, $message) { sub create_post($self, $name, $message) {
$self->pg->db->query(<<~'END_SQL', $name, $message) $self->pg->db->query(<<~'END_SQL', $name, $message)
@ -30,27 +45,24 @@ sub create_post($self, $name, $message) {
END_SQL END_SQL
} }
sub view_posts($self, $this_page, $last_page = undef, @posts) {
$last_page //= get_last_page(@posts);
my $last_post = $this_page * $self->{'max_posts'} - 1;
my $first_post = $last_post - $self->{'max_posts'} + 1;
grep defined, @posts[$first_post..$last_post];
}
sub max_posts($self, $value = undef) { sub max_posts($self, $value = undef) {
$self->{'max_posts'} = $value // $self->{'max_posts'} $self->{'max_posts'} = $value // $self->{'max_posts'}
} }
sub get_last_page($self, @posts) { sub get_last_page($self) {
my $post_count = get_post_count($self);
# Add a page if we have "remainder" posts # Add a page if we have "remainder" posts
if (scalar(@posts) % $self->{'max_posts'}) { if ($post_count % $self->{'max_posts'}) {
sprintf('%d', scalar(@posts) / $self->{'max_posts'}) + 1 sprintf('%d', $post_count / $self->{'max_posts'}) + 1
} }
else { else {
sprintf('%d', scalar(@posts) / $self->{'max_posts'}) sprintf('%d', $post_count / $self->{'max_posts'})
} }
} }
sub get_post_count($self) {
$self->pg->db->query('SELECT count(*) FROM messages;')->text()
}
1; 1;