]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/Msgmap.pm
msgmap: speed up minmax with separate queries
[public-inbox.git] / lib / PublicInbox / Msgmap.pm
index 128330506b151d16afe7cbde83429a06820f4891..feef8ba79ab9a657d8135b0c65ca0186dd7bed51 100644 (file)
@@ -39,6 +39,7 @@ sub dbh_new {
 
 sub new_file {
        my ($class, $f, $writable) = @_;
+       return if !$writable && !-r $f;
 
        my $dbh = dbh_new($f, $writable);
        my $self = bless { dbh => $dbh }, $class;
@@ -91,6 +92,14 @@ sub last_commit {
        $self->meta_accessor('last_commit', $commit);
 }
 
+# v2 uses this to keep track of how up-to-date Xapian is
+# old versions may be automatically GC'ed away in the future,
+# but it's a trivial amount of storage.
+sub last_commit_xap {
+       my ($self, $version, $i, $commit) = @_;
+       $self->meta_accessor("last_xap$version-$i", $commit);
+}
+
 sub created_at {
        my ($self, $second) = @_;
        $self->meta_accessor('created_at', $second);
@@ -129,10 +138,14 @@ sub num_for {
 sub minmax {
        my ($self) = @_;
        my $dbh = $self->{dbh};
-       my $sth = $self->{num_minmax} ||=
-               $dbh->prepare('SELECT MIN(num),MAX(num) FROM msgmap');
+       # breaking MIN and MAX into separate queries speeds up from 250ms
+       # to around 700us with 2.7million messages.
+       my $sth = $dbh->prepare_cached('SELECT MIN(num) FROM msgmap', undef, 1);
        $sth->execute;
-        $sth->fetchrow_array;
+       my $min = $sth->fetchrow_array;
+       $sth = $dbh->prepare_cached('SELECT MAX(num) FROM msgmap', undef, 1);
+       $sth->execute;
+       ($min, $sth->fetchrow_array);
 }
 
 sub mid_prefixes {
@@ -185,17 +198,26 @@ sub create_tables {
 }
 
 # used by NNTP.pm
-sub id_batch {
-       my ($self, $num, $cb) = @_;
+sub ids_after {
+       my ($self, $num) = @_;
+       my $ids = $self->{dbh}->selectcol_arrayref(<<'', undef, $$num);
+SELECT num FROM msgmap WHERE num > ?
+ORDER BY num ASC LIMIT 1000
+
+       $$num = $ids->[-1] if @$ids;
+       $ids;
+}
+
+sub msg_range {
+       my ($self, $beg, $end) = @_;
        my $dbh = $self->{dbh};
-       my $sth = $dbh->prepare('SELECT num FROM msgmap WHERE num > ? '.
-                               'ORDER BY num ASC LIMIT 1000');
-       $sth->execute($num);
-       my $ary = $sth->fetchall_arrayref;
-       @$ary = map { $_->[0] } @$ary;
-       my $nr = scalar @$ary;
-       $cb->($ary) if $nr;
-       $nr;
+       my $attr = { Columns => [] };
+       my $mids = $dbh->selectall_arrayref(<<'', $attr, $$beg, $end);
+SELECT num,mid FROM msgmap WHERE num >= ? AND num <= ?
+ORDER BY num ASC
+
+       $$beg = $mids->[-1]->[0] + 1 if @$mids;
+       $mids
 }
 
 # only used for mapping external serial numbers (e.g. articles from gmane)