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>
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;
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,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 my $msgs = do_get($self, <<"", $opts, @v);
248 SELECT ts,ds,ddd FROM over WHERE $s
250 return $msgs unless wantarray;
252 my $nr = $self->{dbh}->selectrow_array(<<'');
253 SELECT COUNT(num) FROM over WHERE num > 0
259 my ($self, $num) = @_;
260 # caching $sth ourselves is faster than prepare_cached
261 my $sth = $self->{-get_art} //= dbh($self)->prepare(<<'');
262 SELECT num,tid,ds,ts,ddd FROM over WHERE num = ? LIMIT 1
265 my $smsg = $sth->fetchrow_hashref;
266 $smsg ? load_from_row($smsg) : undef;
270 my ($self, $mid, $id, $prev) = @_;
271 my $dbh = dbh($self);
273 unless (defined $$id) {
274 my $sth = $dbh->prepare_cached(<<'', undef, 1);
275 SELECT id FROM msgid WHERE mid = ? LIMIT 1
278 $$id = $sth->fetchrow_array;
279 defined $$id or return;
281 my $sth = $dbh->prepare_cached(<<"", undef, 1);
282 SELECT num FROM id2num WHERE id = ? AND num > ?
283 ORDER BY num ASC LIMIT 1
286 $sth->execute($$id, $$prev);
287 my $num = $sth->fetchrow_array or return;
289 get_art($self, $num);
292 # IMAP search, this is limited by callers to UID_SLICE size (50K)
294 my ($self, $beg, $end, $sql) = @_;
295 my $dbh = dbh($self);
296 my $q = 'SELECT num FROM over WHERE num >= ? AND num <= ?';
298 # This is read-only, anyways; but caller should verify it's
299 # only sending \A[0-9]+\z for ds and ts column ranges
301 $q .= ' ORDER BY num ASC';
302 $dbh->selectcol_arrayref($q, undef, $beg, $end);
307 my $sth = dbh($self)->prepare_cached(<<'', undef, 1);
308 SELECT MAX(num) FROM over WHERE num > 0
311 $sth->fetchrow_array // 0;
315 my ($self, $uid_base, $uid_end) = @_;
316 my $sth = dbh($self)->prepare_cached(<<'', undef, 1);
317 SELECT COUNT(num) FROM over WHERE num > ? AND num <= ?
319 $sth->execute($uid_base, $uid_end);
320 $sth->fetchrow_array;
325 my $dbh = $self->{dbh} or return;
326 my $f = $dbh->sqlite_db_filename;
327 if (my @st = stat($f)) { # did st_dev, st_ino change?
328 my $st = pack('dd', $st[0], $st[1]);
330 # don't actually reopen, just let {dbh} be recreated later
331 dbh_close($self) if $st ne ($self->{st} // $st);
333 warn "W: stat $f: $!\n";