]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/OverIdx.pm
dad3966d9c8ef3b9f7901998cdf0a40369878d40
[public-inbox.git] / lib / PublicInbox / OverIdx.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # for XOVER, OVER in NNTP, and feeds/homepage/threads in PSGI
5 # Unlike Msgmap, this is an _UNSTABLE_ cache which can be
6 # tweaked/updated over time and rebuilt.
7 #
8 # Ghost messages (messages which are only referenced in References/In-Reply-To)
9 # are denoted by a negative NNTP article number.
10 package PublicInbox::OverIdx;
11 use strict;
12 use v5.10.1;
13 use parent qw(PublicInbox::Over);
14 use IO::Handle;
15 use DBI qw(:sql_types); # SQL_BLOB
16 use PublicInbox::MID qw/id_compress mids_for_index references/;
17 use PublicInbox::Smsg qw(subject_normalized);
18 use Compress::Zlib qw(compress);
19 use Carp qw(croak);
20
21 sub dbh_new {
22         my ($self) = @_;
23         my $dbh = $self->SUPER::dbh_new($self->{-no_fsync} ? 2 : 1);
24
25         # 80000 pages (80MiB on SQLite <3.12.0, 320MiB on 3.12.0+)
26         # was found to be good in 2018 during the large LKML import
27         # at the time.  This ought to be configurable based on HW
28         # and inbox size; I suspect it's overkill for many inboxes.
29         $dbh->do('PRAGMA cache_size = 80000');
30
31         create_tables($dbh);
32         $dbh;
33 }
34
35 sub new {
36         my ($class, $f) = @_;
37         my $self = $class->SUPER::new($f);
38         $self->{min_tid} = 0;
39         $self;
40 }
41
42 sub get_counter ($$) {
43         my ($dbh, $key) = @_;
44         my $sth = $dbh->prepare_cached(<<'', undef, 1);
45 SELECT val FROM counter WHERE key = ? LIMIT 1
46
47         $sth->execute($key);
48         $sth->fetchrow_array;
49 }
50
51 sub adj_counter ($$$) {
52         my ($self, $key, $op) = @_;
53         my $dbh = $self->{dbh};
54         my $sth = $dbh->prepare_cached(<<"");
55 UPDATE counter SET val = val $op 1 WHERE key = ?
56
57         $sth->execute($key);
58
59         get_counter($dbh, $key);
60 }
61
62 sub next_tid { adj_counter($_[0], 'thread', '+') }
63 sub next_ghost_num { adj_counter($_[0], 'ghost', '-') }
64
65 sub id_for ($$$$$) {
66         my ($self, $tbl, $id_col, $val_col, $val) = @_;
67         my $dbh = $self->{dbh};
68         my $in = $dbh->prepare_cached(<<"")->execute($val);
69 INSERT OR IGNORE INTO $tbl ($val_col) VALUES (?)
70
71         if ($in == 0) {
72                 my $sth = $dbh->prepare_cached(<<"", undef, 1);
73 SELECT $id_col FROM $tbl WHERE $val_col = ? LIMIT 1
74
75                 $sth->execute($val);
76                 $sth->fetchrow_array;
77         } else {
78                 $dbh->last_insert_id(undef, undef, $tbl, $id_col);
79         }
80 }
81
82 sub ibx_id {
83         my ($self, $eidx_key) = @_;
84         id_for($self, 'inboxes', 'ibx_id', eidx_key => $eidx_key);
85 }
86
87 sub sid {
88         my ($self, $path) = @_;
89         return unless defined $path && $path ne '';
90         id_for($self, 'subject', 'sid', 'path' => $path);
91 }
92
93 sub mid2id {
94         my ($self, $mid) = @_;
95         id_for($self, 'msgid', 'id', 'mid' => $mid);
96 }
97
98 sub delete_by_num {
99         my ($self, $num, $tid_ref) = @_;
100         my $dbh = $self->{dbh};
101         if ($tid_ref) {
102                 my $sth = $dbh->prepare_cached(<<'', undef, 1);
103 SELECT tid FROM over WHERE num = ? LIMIT 1
104
105                 $sth->execute($num);
106                 $$tid_ref = $sth->fetchrow_array; # may be undef
107         }
108         foreach (qw(over id2num)) {
109                 $dbh->prepare_cached(<<"")->execute($num);
110 DELETE FROM $_ WHERE num = ?
111
112         }
113 }
114
115 # this includes ghosts
116 sub each_by_mid {
117         my ($self, $mid, $cols, $cb, @arg) = @_;
118         my $dbh = $self->{dbh};
119
120 =over
121         I originally wanted to stuff everything into a single query:
122
123         SELECT over.* FROM over
124         LEFT JOIN id2num ON over.num = id2num.num
125         LEFT JOIN msgid ON msgid.id = id2num.id
126         WHERE msgid.mid = ? AND over.num >= ?
127         ORDER BY over.num ASC
128         LIMIT 1000
129
130         But it's faster broken out (and we're always in a
131         transaction for subroutines in this file)
132 =cut
133
134         my $sth = $dbh->prepare_cached(<<'', undef, 1);
135 SELECT id FROM msgid WHERE mid = ? LIMIT 1
136
137         $sth->execute($mid);
138         my $id = $sth->fetchrow_array;
139         defined $id or return;
140
141         push(@$cols, 'num');
142         $cols = join(',', map { $_ } @$cols);
143         my $lim = 10;
144         my $prev = get_counter($dbh, 'ghost');
145         while (1) {
146                 $sth = $dbh->prepare_cached(<<"", undef, 1);
147 SELECT num FROM id2num WHERE id = ? AND num >= ?
148 ORDER BY num ASC
149 LIMIT $lim
150
151                 $sth->execute($id, $prev);
152                 my $nums = $sth->fetchall_arrayref;
153                 my $nr = scalar(@$nums) or return;
154                 $prev = $nums->[-1]->[0];
155
156                 $sth = $dbh->prepare_cached(<<"", undef, 1);
157 SELECT $cols FROM over WHERE over.num = ? LIMIT 1
158
159                 foreach (@$nums) {
160                         $sth->execute($_->[0]);
161                         my $smsg = $sth->fetchrow_hashref;
162                         $smsg = PublicInbox::Over::load_from_row($smsg);
163                         $cb->($self, $smsg, @arg) or return;
164                 }
165                 return if $nr != $lim;
166         }
167 }
168
169 sub _resolve_mid_to_tid {
170         my ($self, $smsg, $tid) = @_;
171         my $cur_tid = $smsg->{tid};
172         if (defined $$tid) {
173                 merge_threads($self, $$tid, $cur_tid);
174         } elsif ($cur_tid > $self->{min_tid}) {
175                 $$tid = $cur_tid;
176         } else { # rethreading, queue up dead ghosts
177                 $$tid = next_tid($self);
178                 my $n = $smsg->{num};
179                 if ($n > 0) {
180                         $self->{dbh}->prepare_cached(<<'')->execute($$tid, $n);
181 UPDATE over SET tid = ? WHERE num = ?
182
183                 } elsif ($n < 0) {
184                         push(@{$self->{-ghosts_to_delete}}, $n);
185                 }
186         }
187         1;
188 }
189
190 # this will create a ghost as necessary
191 sub resolve_mid_to_tid {
192         my ($self, $mid) = @_;
193         my $tid;
194         each_by_mid($self, $mid, ['tid'], \&_resolve_mid_to_tid, \$tid);
195         if (my $del = delete $self->{-ghosts_to_delete}) {
196                 delete_by_num($self, $_) for @$del;
197         }
198         $tid // do { # create a new ghost
199                 my $id = mid2id($self, $mid);
200                 my $num = next_ghost_num($self);
201                 $num < 0 or die "ghost num is non-negative: $num\n";
202                 $tid = next_tid($self);
203                 my $dbh = $self->{dbh};
204                 $dbh->prepare_cached(<<'')->execute($num, $tid);
205 INSERT INTO over (num, tid) VALUES (?,?)
206
207                 $dbh->prepare_cached(<<'')->execute($id, $num);
208 INSERT INTO id2num (id, num) VALUES (?,?)
209
210                 $tid;
211         };
212 }
213
214 sub merge_threads {
215         my ($self, $winner_tid, $loser_tid) = @_;
216         return if $winner_tid == $loser_tid;
217         my $dbh = $self->{dbh};
218         $dbh->prepare_cached(<<'')->execute($winner_tid, $loser_tid);
219 UPDATE over SET tid = ? WHERE tid = ?
220
221 }
222
223 sub link_refs {
224         my ($self, $refs, $old_tid) = @_;
225         my $tid;
226
227         if (@$refs) {
228                 # first ref *should* be the thread root,
229                 # but we can never trust clients to do the right thing
230                 my $ref = $refs->[0];
231                 $tid = resolve_mid_to_tid($self, $ref);
232                 merge_threads($self, $tid, $old_tid) if defined $old_tid;
233
234                 # the rest of the refs should point to this tid:
235                 foreach my $i (1..$#$refs) {
236                         $ref = $refs->[$i];
237                         my $ptid = resolve_mid_to_tid($self, $ref);
238                         merge_threads($self, $tid, $ptid);
239                 }
240         } else {
241                 $tid = $old_tid // next_tid($self);
242         }
243         $tid;
244 }
245
246 sub parse_references ($$$) {
247         my ($smsg, $hdr, $mids) = @_;
248         my $refs = references($hdr);
249         push(@$refs, @$mids) if scalar(@$mids) > 1;
250         return $refs if scalar(@$refs) == 0;
251
252         # prevent circular references here:
253         my %seen = ( $smsg->{mid} => 1 );
254         my @keep;
255         foreach my $ref (@$refs) {
256                 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
257                         warn "References: <$ref> too long, ignoring\n";
258                         next;
259                 }
260                 push(@keep, $ref) unless $seen{$ref}++;
261         }
262         $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
263         \@keep;
264 }
265
266 # normalize subjects so they are suitable as pathnames for URLs
267 # XXX: consider for removal
268 sub subject_path ($) {
269         my ($subj) = @_;
270         $subj = subject_normalized($subj);
271         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
272         lc($subj);
273 }
274
275 sub ddd_for ($) {
276         my ($smsg) = @_;
277         my $dd = $smsg->to_doc_data;
278         utf8::encode($dd);
279         compress($dd);
280 }
281
282 sub add_overview {
283         my ($self, $eml, $smsg) = @_;
284         $smsg->{lines} = $eml->body_raw =~ tr!\n!\n!;
285         my $mids = mids_for_index($eml);
286         my $refs = parse_references($smsg, $eml, $mids);
287         $mids->[0] //= $smsg->{mid} //= $eml->{-lei_fake_mid};
288         $smsg->{mid} //= '';
289         my $subj = $smsg->{subject};
290         my $xpath;
291         if ($subj ne '') {
292                 $xpath = subject_path($subj);
293                 $xpath = id_compress($xpath);
294         }
295         add_over($self, $smsg, $mids, $refs, $xpath, ddd_for($smsg));
296 }
297
298 sub _add_over {
299         my ($self, $smsg, $mid, $refs, $old_tid, $v) = @_;
300         my $cur_tid = $smsg->{tid};
301         my $n = $smsg->{num};
302         die "num must not be zero for $mid" if !$n;
303         my $cur_valid = $cur_tid > $self->{min_tid};
304
305         if ($n > 0) { # regular mail
306                 if ($cur_valid) {
307                         $$old_tid //= $cur_tid;
308                         merge_threads($self, $$old_tid, $cur_tid);
309                 } else {
310                         $$old_tid //= next_tid($self);
311                 }
312         } elsif ($n < 0) { # ghost
313                 $$old_tid //= $cur_valid ? $cur_tid : next_tid($self);
314                 $$old_tid = link_refs($self, $refs, $$old_tid);
315                 delete_by_num($self, $n);
316                 $$v++;
317         }
318         1;
319 }
320
321 sub add_over {
322         my ($self, $smsg, $mids, $refs, $xpath, $ddd) = @_;
323         my $old_tid;
324         my $vivified = 0;
325         my $num = $smsg->{num};
326
327         begin_lazy($self);
328         delete_by_num($self, $num, \$old_tid);
329         $old_tid = undef if ($old_tid // 0) <= $self->{min_tid};
330         foreach my $mid (@$mids) {
331                 my $v = 0;
332                 each_by_mid($self, $mid, ['tid'], \&_add_over,
333                                 $mid, $refs, \$old_tid, \$v);
334                 $v > 1 and warn "BUG: vivified multiple ($v) ghosts for $mid\n";
335                 $vivified += $v;
336         }
337         $smsg->{tid} = $vivified ? $old_tid : link_refs($self, $refs, $old_tid);
338         $smsg->{sid} = sid($self, $xpath);
339         my $dbh = $self->{dbh};
340         my $sth = $dbh->prepare_cached(<<'');
341 INSERT INTO over (num, tid, sid, ts, ds, ddd)
342 VALUES (?,?,?,?,?,?)
343
344         my $nc = 1;
345         $sth->bind_param($nc, $num);
346         $sth->bind_param(++$nc, $smsg->{$_}) for (qw(tid sid ts ds));
347         $sth->bind_param(++$nc, $ddd, SQL_BLOB);
348         $sth->execute;
349         $sth = $dbh->prepare_cached(<<'');
350 INSERT INTO id2num (id, num) VALUES (?,?)
351
352         foreach my $mid (@$mids) {
353                 my $id = mid2id($self, $mid);
354                 $sth->execute($id, $num);
355         }
356 }
357
358 sub _remove_oid {
359         my ($self, $smsg, $oid, $removed) = @_;
360         if (!defined($oid) || $smsg->{blob} eq $oid) {
361                 delete_by_num($self, $smsg->{num});
362                 push @$removed, $smsg->{num};
363         }
364         1;
365 }
366
367 # returns number of removed messages in scalar context,
368 # array of removed article numbers in array context.
369 # $oid may be undef to match only on $mid
370 sub remove_oid {
371         my ($self, $oid, $mid) = @_;
372         my $removed = [];
373         begin_lazy($self);
374         each_by_mid($self, $mid, ['ddd'], \&_remove_oid, $oid, $removed);
375         @$removed;
376 }
377
378 sub _num_mid0_for_oid {
379         my ($self, $smsg, $oid, $res) = @_;
380         my $blob = $smsg->{blob};
381         return 1 if (!defined($blob) || $blob ne $oid); # continue;
382         @$res = ($smsg->{num}, $smsg->{mid});
383         0; # done
384 }
385
386 sub num_mid0_for_oid {
387         my ($self, $oid, $mid) = @_;
388         my $res = [];
389         begin_lazy($self);
390         each_by_mid($self, $mid, ['ddd'], \&_num_mid0_for_oid, $oid, $res);
391         @$res, # ($num, $mid0);
392 }
393
394 sub create_tables {
395         my ($dbh) = @_;
396
397         $dbh->do(<<'');
398 CREATE TABLE IF NOT EXISTS over (
399         num INTEGER PRIMARY KEY NOT NULL, /* NNTP article number == IMAP UID */
400         tid INTEGER NOT NULL, /* THREADID (IMAP REFERENCES threading, JMAP) */
401         sid INTEGER, /* Subject ID (IMAP ORDEREDSUBJECT "threading") */
402         ts INTEGER, /* IMAP INTERNALDATE (Received: header, git commit time) */
403         ds INTEGER, /* RFC-2822 sent Date: header, git author time */
404         ddd VARBINARY /* doc-data-deflated (->to_doc_data, ->load_from_data) */
405 )
406
407         $dbh->do('CREATE INDEX IF NOT EXISTS idx_tid ON over (tid)');
408         $dbh->do('CREATE INDEX IF NOT EXISTS idx_sid ON over (sid)');
409         $dbh->do('CREATE INDEX IF NOT EXISTS idx_ts ON over (ts)');
410         $dbh->do('CREATE INDEX IF NOT EXISTS idx_ds ON over (ds)');
411
412         $dbh->do(<<'');
413 CREATE TABLE IF NOT EXISTS counter (
414         key VARCHAR(8) PRIMARY KEY NOT NULL,
415         val INTEGER DEFAULT 0,
416         UNIQUE (key)
417 )
418
419         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('thread')");
420         $dbh->do("INSERT OR IGNORE INTO counter (key) VALUES ('ghost')");
421
422         $dbh->do(<<'');
423 CREATE TABLE IF NOT EXISTS subject (
424         sid INTEGER PRIMARY KEY AUTOINCREMENT,
425         path VARCHAR(40) NOT NULL, /* SHA-1 of normalized subject */
426         UNIQUE (path)
427 )
428
429         $dbh->do(<<'');
430 CREATE TABLE IF NOT EXISTS id2num (
431         id INTEGER NOT NULL, /* <=> msgid.id */
432         num INTEGER NOT NULL,
433         UNIQUE (id, num)
434 )
435
436         # performance critical:
437         $dbh->do('CREATE INDEX IF NOT EXISTS idx_inum ON id2num (num)');
438         $dbh->do('CREATE INDEX IF NOT EXISTS idx_id ON id2num (id)');
439
440         $dbh->do(<<'');
441 CREATE TABLE IF NOT EXISTS msgid (
442         id INTEGER PRIMARY KEY AUTOINCREMENT, /* <=> id2num.id */
443         mid VARCHAR(244) NOT NULL,
444         UNIQUE (mid)
445 )
446
447 }
448
449 sub commit_lazy {
450         my ($self) = @_;
451         delete $self->{txn} or return;
452         $self->{dbh}->commit;
453 }
454
455 sub begin_lazy {
456         my ($self) = @_;
457         return if $self->{txn};
458         my $dbh = $self->dbh or return;
459         $dbh->begin_work;
460         # $dbh->{Profile} = 2;
461         $self->{txn} = 1;
462 }
463
464 sub rollback_lazy {
465         my ($self) = @_;
466         delete $self->{txn} or return;
467         $self->{dbh}->rollback;
468 }
469
470 sub dbh_close {
471         my ($self) = @_;
472         die "in transaction" if $self->{txn};
473         $self->SUPER::dbh_close;
474 }
475
476 sub create {
477         my ($self) = @_;
478         my $fn = $self->{filename} // do {
479                 Carp::confess('BUG: no {filename}') unless $self->{dbh};
480                 return;
481         };
482         unless (-r $fn) {
483                 require File::Path;
484                 require File::Basename;
485                 File::Path::mkpath(File::Basename::dirname($fn));
486         }
487         # create the DB:
488         PublicInbox::Over::dbh($self);
489         $self->dbh_close;
490 }
491
492 sub rethread_prepare {
493         my ($self, $opt) = @_;
494         return unless $opt->{rethread};
495         begin_lazy($self);
496         my $min = $self->{min_tid} = get_counter($self->{dbh}, 'thread') // 0;
497         my $pr = $opt->{-progress};
498         $pr->("rethread min THREADID ".($min + 1)."\n") if $pr && $min;
499 }
500
501 sub rethread_done {
502         my ($self, $opt) = @_;
503         return unless $opt->{rethread} && $self->{txn};
504         defined(my $min = $self->{min_tid}) or croak('BUG: no min_tid');
505         my $dbh = $self->{dbh} or croak('BUG: no dbh');
506         my $rows = $dbh->selectall_arrayref(<<'', { Slice => {} }, $min);
507 SELECT num,tid FROM over WHERE num < 0 AND tid < ?
508
509         my $show_id = $dbh->prepare('SELECT id FROM id2num WHERE num = ?');
510         my $show_mid = $dbh->prepare('SELECT mid FROM msgid WHERE id = ?');
511         my $pr = $opt->{-progress};
512         my $total = 0;
513         for my $r (@$rows) {
514                 my $exp = 0;
515                 $show_id->execute($r->{num});
516                 while (defined(my $id = $show_id->fetchrow_array)) {
517                         ++$exp;
518                         $show_mid->execute($id);
519                         my $mid = $show_mid->fetchrow_array;
520                         if (!defined($mid)) {
521                                 warn <<EOF;
522 E: ghost NUM=$r->{num} ID=$id THREADID=$r->{tid} has no Message-ID
523 EOF
524                                 next;
525                         }
526                         $pr->(<<EOM) if $pr;
527 I: ghost $r->{num} <$mid> THREADID=$r->{tid} culled
528 EOM
529                 }
530                 delete_by_num($self, $r->{num});
531         }
532         $pr->("I: rethread culled $total ghosts\n") if $pr && $total;
533 }
534
535 # used for cross-inbox search
536 sub eidx_prep ($) {
537         my ($self) = @_;
538         $self->{-eidx_prep} //= do {
539                 my $dbh = $self->dbh;
540                 $dbh->do(<<"");
541 INSERT OR IGNORE INTO counter (key) VALUES ('eidx_docid')
542
543                 $dbh->do(<<'');
544 CREATE TABLE IF NOT EXISTS inboxes (
545         ibx_id INTEGER PRIMARY KEY AUTOINCREMENT,
546         eidx_key VARCHAR(255) NOT NULL, /* {newsgroup} // {inboxdir} */
547         UNIQUE (eidx_key)
548 )
549
550                 $dbh->do(<<'');
551 CREATE TABLE IF NOT EXISTS xref3 (
552         docid INTEGER NOT NULL, /* <=> over.num */
553         ibx_id INTEGER NOT NULL, /* <=> inboxes.ibx_id */
554         xnum INTEGER NOT NULL, /* NNTP article number in ibx */
555         oidbin VARBINARY NOT NULL, /* 20-byte SHA-1 or 32-byte SHA-256 */
556         UNIQUE (docid, ibx_id, xnum, oidbin)
557 )
558
559         $dbh->do('CREATE INDEX IF NOT EXISTS idx_docid ON xref3 (docid)');
560
561         # performance critical, this is not UNIQUE since we may need to
562         # tolerate some old bugs from indexing mirrors
563         $dbh->do('CREATE INDEX IF NOT EXISTS idx_nntp ON '.
564                 'xref3 (oidbin,xnum,ibx_id)');
565
566                 $dbh->do(<<'');
567 CREATE TABLE IF NOT EXISTS eidx_meta (
568         key VARCHAR(255) PRIMARY KEY,
569         val VARCHAR(255) NOT NULL
570 )
571
572                 # A queue of current docids which need reindexing.
573                 # eidxq persists across aborted -extindex invocations
574                 # Currently used for "-extindex --reindex" for Xapian
575                 # data, but may be used in more places down the line.
576                 $dbh->do(<<'');
577 CREATE TABLE IF NOT EXISTS eidxq (
578         docid INTEGER PRIMARY KEY NOT NULL
579 )
580
581                 $dbh;
582         };
583 }
584
585 sub eidx_meta { # requires transaction
586         my ($self, $key, $val) = @_;
587
588         my $sql = 'SELECT val FROM eidx_meta WHERE key = ? LIMIT 1';
589         my $dbh = $self->{dbh};
590         defined($val) or return $dbh->selectrow_array($sql, undef, $key);
591
592         my $prev = $dbh->selectrow_array($sql, undef, $key);
593         if (defined $prev) {
594                 $sql = 'UPDATE eidx_meta SET val = ? WHERE key = ?';
595                 $dbh->do($sql, undef, $val, $key);
596         } else {
597                 $sql = 'INSERT INTO eidx_meta (key,val) VALUES (?,?)';
598                 $dbh->do($sql, undef, $key, $val);
599         }
600         $prev;
601 }
602
603 sub eidx_max {
604         my ($self) = @_;
605         get_counter($self->{dbh}, 'eidx_docid');
606 }
607
608 sub add_xref3 {
609         my ($self, $docid, $xnum, $oidhex, $eidx_key) = @_;
610         begin_lazy($self);
611         my $ibx_id = ibx_id($self, $eidx_key);
612         my $oidbin = pack('H*', $oidhex);
613         my $sth = $self->{dbh}->prepare_cached(<<'');
614 INSERT OR IGNORE INTO xref3 (docid, ibx_id, xnum, oidbin) VALUES (?, ?, ?, ?)
615
616         $sth->bind_param(1, $docid);
617         $sth->bind_param(2, $ibx_id);
618         $sth->bind_param(3, $xnum);
619         $sth->bind_param(4, $oidbin, SQL_BLOB);
620         $sth->execute;
621 }
622
623 # returns remaining reference count to $docid
624 sub remove_xref3 {
625         my ($self, $docid, $oidhex, $eidx_key, $rm_eidx_info) = @_;
626         begin_lazy($self);
627         my $oidbin = pack('H*', $oidhex);
628         my ($sth, $ibx_id);
629         if (defined $eidx_key) {
630                 $ibx_id = ibx_id($self, $eidx_key);
631                 $sth = $self->{dbh}->prepare_cached(<<'');
632 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ? AND oidbin = ?
633
634                 $sth->bind_param(1, $docid);
635                 $sth->bind_param(2, $ibx_id);
636                 $sth->bind_param(3, $oidbin, SQL_BLOB);
637         } else {
638                 $sth = $self->{dbh}->prepare_cached(<<'');
639 DELETE FROM xref3 WHERE docid = ? AND oidbin = ?
640
641                 $sth->bind_param(1, $docid);
642                 $sth->bind_param(2, $oidbin, SQL_BLOB);
643         }
644         $sth->execute;
645         $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
646 SELECT COUNT(*) FROM xref3 WHERE docid = ?
647
648         $sth->execute($docid);
649         my $nr = $sth->fetchrow_array;
650         if ($nr == 0) {
651                 delete_by_num($self, $docid);
652         } elsif (defined($ibx_id) && $rm_eidx_info) {
653                 # if deduplication rules in ContentHash change, it's
654                 # possible a docid can have multiple rows with the
655                 # same ibx_id.  This governs whether or not we call
656                 # ->shard_remove_eidx_info in ExtSearchIdx.
657                 $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
658 SELECT COUNT(*) FROM xref3 WHERE docid = ? AND ibx_id = ?
659
660                 $sth->execute($docid, $ibx_id);
661                 my $count = $sth->fetchrow_array;
662                 $$rm_eidx_info = ($count == 0);
663         }
664         $nr;
665 }
666
667 # for when an xref3 goes missing, this does NOT update {ts}
668 sub update_blob {
669         my ($self, $smsg, $oidhex) = @_;
670         my $sth = $self->{dbh}->prepare(<<'');
671 UPDATE over SET ddd = ? WHERE num = ?
672
673         $smsg->{blob} = $oidhex;
674         $sth->bind_param(1, ddd_for($smsg), SQL_BLOB);
675         $sth->bind_param(2, $smsg->{num});
676         $sth->execute;
677 }
678
679 sub eidxq_add {
680         my ($self, $docid) = @_;
681         $self->dbh->prepare_cached(<<'')->execute($docid);
682 INSERT OR IGNORE INTO eidxq (docid) VALUES (?)
683
684 }
685
686 sub eidxq_del {
687         my ($self, $docid) = @_;
688         $self->dbh->prepare_cached(<<'')->execute($docid);
689 DELETE FROM eidxq WHERE docid = ?
690
691 }
692
693 sub blob_exists {
694         my ($self, $oidhex) = @_;
695         my $sth = $self->dbh->prepare_cached(<<'', undef, 1);
696 SELECT COUNT(*) FROM xref3 WHERE oidbin = ?
697
698         $sth->bind_param(1, pack('H*', $oidhex), SQL_BLOB);
699         $sth->execute;
700         $sth->fetchrow_array;
701 }
702
703 1;