1 # Copyright (C) 2018-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # for XOVER, OVER in NNTP, and feeds/homepage/threads in PSGI
5 # Unlike Msgmap, this is an _UNSTABLE_ database which can be
6 # tweaked/updated over time and rebuilt.
7 package PublicInbox::Over;
10 use DBI qw(:sql_types); # SQL_BLOB
12 use PublicInbox::Smsg;
13 use Compress::Zlib qw(uncompress);
14 use constant DEFAULT_LIMIT => 1000;
18 my $f = delete $self->{filename};
19 if (!-f $f) { # SQLite defaults mode to 0644, we want 0666
21 require PublicInbox::Spawn;
22 open my $fh, '+>>', $f or die "failed to open $f: $!";
23 PublicInbox::Spawn::nodatacow_fd(fileno($fh));
25 $self->{filename} = $f; # die on stat() below:
31 @st = stat($f) or die "failed to stat $f: $!";
32 $st = pack('dd', $st[0], $st[1]); # 0: dev, 1: inode
33 $dbh = DBI->connect("dbi:SQLite:dbname=$f",'','', {
38 sqlite_use_immediate_transaction => 1,
41 @st = stat($f) or die "failed to stat $f: $!";
42 $st = pack('dd', $st[0], $st[1]);
43 } while ($st ne $self->{st} && $tries++ < 3);
44 warn "W: $f: .st_dev, .st_ino unstable\n" if $st ne $self->{st};
47 # TRUNCATE reduces I/O compared to the default (DELETE).
49 # Do not use WAL by default since we expect the case
50 # where any users may read via read-only daemons
51 # (-httpd/-imapd/-nntpd); but only a single user has
52 # write permissions for -watch/-mda.
54 # Read-only WAL support in SQLite 3.22.0 (2018-01-22)
55 # doesn't do what we need: it is only intended for
56 # immutable read-only media (e.g. CD-ROM) and not
57 # usable for our use case described above.
59 # If an admin is willing to give read-only daemons R/W
60 # permissions; they can enable WAL manually and we will
61 # respect that by not clobbering it.
62 my $jm = $dbh->selectrow_array('PRAGMA journal_mode');
63 $dbh->do('PRAGMA journal_mode = TRUNCATE') if $jm ne 'wal';
65 $dbh->do('PRAGMA synchronous = OFF') if $rw > 1;
72 bless { filename => $f }, $class;
77 if (my $dbh = delete $self->{dbh}) {
78 delete $self->{-get_art};
79 $self->{filename} = $dbh->sqlite_db_filename;
83 sub dbh ($) { $_[0]->{dbh} //= $_[0]->dbh_new } # dbh_new may be subclassed
85 sub load_from_row ($;$) {
86 my ($smsg, $cull) = @_;
87 bless $smsg, 'PublicInbox::Smsg';
88 if (defined(my $data = delete $smsg->{ddd})) {
89 $data = uncompress($data);
90 PublicInbox::Smsg::load_from_data($smsg, $data);
92 # saves over 600K for 1000+ message threads
93 PublicInbox::Smsg::psgi_cull($smsg) if $cull;
99 my ($self, $sql, $opts, @args) = @_;
100 my $lim = (($opts->{limit} || 0) + 0) || DEFAULT_LIMIT;
101 $sql .= "LIMIT $lim";
102 my $msgs = dbh($self)->selectall_arrayref($sql, { Slice => {} }, @args);
103 my $cull = $opts->{cull};
104 load_from_row($_, $cull) for @$msgs;
109 my ($self, $beg, $end) = @_;
110 do_get($self, <<'', {}, $beg, $end);
111 SELECT num,ts,ds,ddd FROM over WHERE num >= ? AND num <= ?
117 my ($self, $ts, $prev) = @_;
118 do_get($self, <<'', {}, $ts, $prev);
119 SELECT num,ddd FROM over WHERE ts >= ? AND num > ?
126 my $nr = scalar(@_) or return [];
127 my $in = '?' . (',?' x ($nr - 1));
128 do_get($self, <<"", { cull => 1, limit => $nr }, @_);
129 SELECT num,ts,ds,ddd FROM over WHERE num IN ($in)
133 sub nothing () { wantarray ? (0, []) : [] };
136 my ($self, $mid, $prev) = @_;
137 my $dbh = dbh($self);
138 my $opts = { cull => 1 };
140 my $id = $dbh->selectrow_array(<<'', undef, $mid);
141 SELECT id FROM msgid WHERE mid = ? LIMIT 1
143 defined $id or return nothing;
145 my $num = $dbh->selectrow_array(<<'', undef, $id);
146 SELECT num FROM id2num WHERE id = ? AND num > 0
147 ORDER BY num ASC LIMIT 1
149 defined $num or return nothing;
151 my ($tid, $sid) = $dbh->selectrow_array(<<'', undef, $num);
152 SELECT tid,sid FROM over WHERE num = ? LIMIT 1
154 defined $tid or return nothing; # $sid may be undef
156 my $cond_all = '(tid = ? OR sid = ?) AND num > ?';
159 if ($prev) { # mboxrd stream, only
160 $num = $prev->{num} || 0;
164 my $cols = 'num,ts,ds,ddd';
166 return do_get($self, <<"", $opts, $tid, $sid, $num);
167 SELECT $cols FROM over WHERE $cond_all
168 ORDER BY $sort_col ASC
172 # HTML view always wants an array and never uses $prev,
173 # but the mbox stream never wants an array and always has $prev
174 die '$prev not supported with wantarray' if $prev;
175 my $nr = $dbh->selectrow_array(<<"", undef, $tid, $sid, $num);
176 SELECT COUNT(num) FROM over WHERE $cond_all
178 # giant thread, prioritize strict (tid) matches and throw
179 # in the loose (sid) matches at the end
180 my $msgs = do_get($self, <<"", $opts, $tid, $num);
181 SELECT $cols FROM over WHERE tid = ? AND num > ?
182 ORDER BY $sort_col ASC
184 # do we have room for loose matches? get the most recent ones, first:
185 my $lim = DEFAULT_LIMIT - scalar(@$msgs);
187 $opts->{limit} = $lim;
188 my $loose = do_get($self, <<"", $opts, $tid, $sid, $num);
189 SELECT $cols FROM over WHERE tid != ? AND sid = ? AND num > ?
190 ORDER BY $sort_col DESC
192 # TODO separate strict and loose matches here once --reindex
193 # is fixed to preserve `tid' properly
194 push @$msgs, @$loose;
199 # strict `tid' matches, only, for thread-expanded mbox.gz search results
200 # and future CLI interface
201 # returns true if we have IDs, undef if not
203 my ($self, $ctx) = @_;
204 my $dbh = dbh($self);
206 defined(my $num = $ctx->{ids}->[0]) or return;
207 my ($tid) = $dbh->selectrow_array(<<'', undef, $num);
208 SELECT tid FROM over WHERE num = ?
212 SELECT num FROM over WHERE tid = ? AND num > ?
213 ORDER BY num ASC LIMIT 1000
215 my $xids = $dbh->selectcol_arrayref($sql, undef, $tid,
217 if (scalar(@$xids)) {
218 $ctx->{prev} = $xids->[-1];
219 $ctx->{xids} = $xids;
224 shift @{$ctx->{ids}};
229 my ($self, $opts, $after, $before) = @_;
231 if (defined($before)) {
232 if (defined($after)) {
233 $s = '+num > 0 AND ts >= ? AND ts <= ? ORDER BY ts DESC';
234 @v = ($after, $before);
236 $s = '+num > 0 AND ts <= ? ORDER BY ts DESC';
240 if (defined($after)) {
241 $s = '+num > 0 AND ts >= ? ORDER BY ts ASC';
244 $s = '+num > 0 ORDER BY ts DESC';
247 do_get($self, <<"", $opts, @v);
248 SELECT ts,ds,ddd FROM over WHERE $s
253 my ($self, $num) = @_;
254 # caching $sth ourselves is faster than prepare_cached
255 my $sth = $self->{-get_art} //= dbh($self)->prepare(<<'');
256 SELECT num,tid,ds,ts,ddd FROM over WHERE num = ? LIMIT 1
259 my $smsg = $sth->fetchrow_hashref;
260 $smsg ? load_from_row($smsg) : undef;
264 my ($self, $num, $raw) = @_;
265 my $dbh = dbh($self);
266 my $sth = $dbh->prepare_cached(<<'', undef, 1);
267 SELECT ibx_id,xnum,oidbin FROM xref3 WHERE docid = ? ORDER BY ibx_id,xnum ASC
270 my $rows = $sth->fetchall_arrayref;
271 return $rows if $raw;
272 my $eidx_key_sth = $dbh->prepare_cached(<<'', undef, 1);
273 SELECT eidx_key FROM inboxes WHERE ibx_id = ?
277 $eidx_key_sth->execute($r->[0]);
278 my $eidx_key = $eidx_key_sth->fetchrow_array;
279 $eidx_key //= "missing://ibx_id=$r->[0]";
280 "$eidx_key:$r->[1]:".unpack('H*', $r->[2]);
285 my ($self, $mid, $id, $prev) = @_;
286 my $dbh = dbh($self);
288 unless (defined $$id) {
289 my $sth = $dbh->prepare_cached(<<'', undef, 1);
290 SELECT id FROM msgid WHERE mid = ? LIMIT 1
293 $$id = $sth->fetchrow_array;
294 defined $$id or return;
296 my $sth = $dbh->prepare_cached(<<"", undef, 1);
297 SELECT num FROM id2num WHERE id = ? AND num > ?
298 ORDER BY num ASC LIMIT 1
301 $sth->execute($$id, $$prev);
302 my $num = $sth->fetchrow_array or return;
304 get_art($self, $num);
307 # IMAP search, this is limited by callers to UID_SLICE size (50K)
309 my ($self, $beg, $end, $sql) = @_;
310 my $dbh = dbh($self);
311 my $q = 'SELECT num FROM over WHERE num >= ? AND num <= ?';
313 # This is read-only, anyways; but caller should verify it's
314 # only sending \A[0-9]+\z for ds and ts column ranges
316 $q .= ' ORDER BY num ASC';
317 $dbh->selectcol_arrayref($q, undef, $beg, $end);
322 my $sth = dbh($self)->prepare_cached(<<'', undef, 1);
323 SELECT MAX(num) FROM over WHERE num > 0
326 $sth->fetchrow_array // 0;
330 my ($self, $uid_base, $uid_end) = @_;
331 my $sth = dbh($self)->prepare_cached(<<'', undef, 1);
332 SELECT COUNT(num) FROM over WHERE num > ? AND num <= ?
334 $sth->execute($uid_base, $uid_end);
335 $sth->fetchrow_array;
340 my $dbh = $self->{dbh} or return;
341 my $f = $dbh->sqlite_db_filename;
342 if (my @st = stat($f)) { # did st_dev, st_ino change?
343 my $st = pack('dd', $st[0], $st[1]);
345 # don't actually reopen, just let {dbh} be recreated later
346 dbh_close($self) if $st ne ($self->{st} // $st);
348 warn "W: stat $f: $!\n";
353 my ($self, $oidbin) = @_;
355 my $sth = $self->dbh->prepare_cached(<<'', undef, 1);
356 SELECT docid FROM xref3 WHERE oidbin = ? ORDER BY docid ASC
358 $sth->bind_param(1, $oidbin, SQL_BLOB);
360 my $tmp = $sth->fetchall_arrayref;
361 map { $_->[0] } @$tmp;
363 my $sth = $self->dbh->prepare_cached(<<'', undef, 1);
364 SELECT COUNT(*) FROM xref3 WHERE oidbin = ?
366 $sth->bind_param(1, $oidbin, SQL_BLOB);
368 $sth->fetchrow_array;
372 sub blob_exists { oidbin_exists($_[0], pack('H*', $_[1])) }
376 my ($self, $num) = @_;
377 my $ids = dbh($self)->selectcol_arrayref(<<'', undef, $$num);
378 SELECT num FROM over WHERE num > ?
379 ORDER BY num ASC LIMIT 1000
381 $$num = $ids->[-1] if @$ids;