+sub get_xref3 {
+ my ($self, $num, $raw) = @_;
+ my $dbh = dbh($self);
+ my $sth = $dbh->prepare_cached(<<'', undef, 1);
+SELECT ibx_id,xnum,oidbin FROM xref3 WHERE docid = ? ORDER BY ibx_id,xnum ASC
+
+ $sth->execute($num);
+ my $rows = $sth->fetchall_arrayref;
+ return $rows if $raw;
+ my $eidx_key_sth = $dbh->prepare_cached(<<'', undef, 1);
+SELECT eidx_key FROM inboxes WHERE ibx_id = ?
+
+ [ map {
+ my $r = $_;
+ $eidx_key_sth->execute($r->[0]);
+ my $eidx_key = $eidx_key_sth->fetchrow_array;
+ $eidx_key //= "missing://ibx_id=$r->[0]";
+ "$eidx_key:$r->[1]:".unpack('H*', $r->[2]);
+ } @$rows ];
+}
+
+sub next_by_mid {
+ my ($self, $mid, $id, $prev) = @_;
+ my $dbh = dbh($self);
+
+ unless (defined $$id) {
+ my $sth = $dbh->prepare_cached(<<'', undef, 1);
+ SELECT id FROM msgid WHERE mid = ? LIMIT 1
+
+ $sth->execute($mid);
+ $$id = $sth->fetchrow_array;
+ defined $$id or return;
+ }
+ my $sth = $dbh->prepare_cached(<<"", undef, 1);
+SELECT num FROM id2num WHERE id = ? AND num > ?
+ORDER BY num ASC LIMIT 1
+
+ $$prev ||= 0;
+ $sth->execute($$id, $$prev);
+ my $num = $sth->fetchrow_array or return;
+ $$prev = $num;
+ get_art($self, $num);
+}
+
+# IMAP search, this is limited by callers to UID_SLICE size (50K)
+sub uid_range {
+ my ($self, $beg, $end, $sql) = @_;
+ my $dbh = dbh($self);
+ my $q = 'SELECT num FROM over WHERE num >= ? AND num <= ?';
+
+ # This is read-only, anyways; but caller should verify it's
+ # only sending \A[0-9]+\z for ds and ts column ranges
+ $q .= $$sql if $sql;
+ $q .= ' ORDER BY num ASC';
+ $dbh->selectcol_arrayref($q, undef, $beg, $end);
+}
+
+sub max {
+ my ($self) = @_;
+ my $sth = dbh($self)->prepare_cached(<<'', undef, 1);
+SELECT MAX(num) FROM over WHERE num > 0
+
+ $sth->execute;
+ $sth->fetchrow_array // 0;
+}
+
+sub imap_exists {
+ my ($self, $uid_base, $uid_end) = @_;
+ my $sth = dbh($self)->prepare_cached(<<'', undef, 1);
+SELECT COUNT(num) FROM over WHERE num > ? AND num <= ?
+
+ $sth->execute($uid_base, $uid_end);
+ $sth->fetchrow_array;
+}
+
+sub check_inodes {
+ my ($self) = @_;
+ my $dbh = $self->{dbh} or return;
+ my $f = $dbh->sqlite_db_filename;
+ if (my @st = stat($f)) { # did st_dev, st_ino change?
+ my $st = pack('dd', $st[0], $st[1]);
+
+ # don't actually reopen, just let {dbh} be recreated later
+ dbh_close($self) if $st ne ($self->{st} // $st);
+ } else {
+ warn "W: stat $f: $!\n";
+ }
+}
+
+sub oidbin_exists {
+ my ($self, $oidbin) = @_;
+ if (wantarray) {
+ my $sth = $self->dbh->prepare_cached(<<'', undef, 1);
+SELECT docid FROM xref3 WHERE oidbin = ? ORDER BY docid ASC
+
+ $sth->bind_param(1, $oidbin, SQL_BLOB);
+ $sth->execute;
+ my $tmp = $sth->fetchall_arrayref;
+ map { $_->[0] } @$tmp;
+ } else {
+ my $sth = $self->dbh->prepare_cached(<<'', undef, 1);
+SELECT COUNT(*) FROM xref3 WHERE oidbin = ?
+
+ $sth->bind_param(1, $oidbin, SQL_BLOB);
+ $sth->execute;
+ $sth->fetchrow_array;
+ }
+}
+
+sub blob_exists { oidbin_exists($_[0], pack('H*', $_[1])) }
+
+# used by NNTP.pm
+sub ids_after {