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 connect { $_[0]->{dbh} //= $_[0]->dbh_new }
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 $dbh = $self->connect;
101 my $lim = (($opts->{limit} || 0) + 0) || DEFAULT_LIMIT;
102 $sql .= "LIMIT $lim";
103 my $msgs = $dbh->selectall_arrayref($sql, { Slice => {} }, @args);
104 my $cull = $opts->{cull};
105 load_from_row($_, $cull) for @$msgs;
110 my ($self, $beg, $end) = @_;
111 do_get($self, <<'', {}, $beg, $end);
112 SELECT num,ts,ds,ddd FROM over WHERE num >= ? AND num <= ?
118 my ($self, $ts, $prev) = @_;
119 do_get($self, <<'', {}, $ts, $prev);
120 SELECT num,ddd FROM over WHERE ts >= ? AND num > ?
127 my $nr = scalar(@_) or return [];
128 my $in = '?' . (',?' x ($nr - 1));
129 do_get($self, <<"", { cull => 1, limit => $nr }, @_);
130 SELECT num,ds,ddd FROM over WHERE num IN ($in)
134 sub nothing () { wantarray ? (0, []) : [] };
137 my ($self, $mid, $prev) = @_;
138 my $dbh = $self->connect;
139 my $opts = { cull => 1 };
141 my $id = $dbh->selectrow_array(<<'', undef, $mid);
142 SELECT id FROM msgid WHERE mid = ? LIMIT 1
144 defined $id or return nothing;
146 my $num = $dbh->selectrow_array(<<'', undef, $id);
147 SELECT num FROM id2num WHERE id = ? AND num > 0
148 ORDER BY num ASC LIMIT 1
150 defined $num or return nothing;
152 my ($tid, $sid) = $dbh->selectrow_array(<<'', undef, $num);
153 SELECT tid,sid FROM over WHERE num = ? LIMIT 1
155 defined $tid or return nothing; # $sid may be undef
157 my $cond_all = '(tid = ? OR sid = ?) AND num > ?';
160 if ($prev) { # mboxrd stream, only
161 $num = $prev->{num} || 0;
165 my $cols = 'num,ts,ds,ddd';
167 return do_get($self, <<"", $opts, $tid, $sid, $num);
168 SELECT $cols FROM over WHERE $cond_all
169 ORDER BY $sort_col ASC
173 # HTML view always wants an array and never uses $prev,
174 # but the mbox stream never wants an array and always has $prev
175 die '$prev not supported with wantarray' if $prev;
176 my $nr = $dbh->selectrow_array(<<"", undef, $tid, $sid, $num);
177 SELECT COUNT(num) FROM over WHERE $cond_all
179 # giant thread, prioritize strict (tid) matches and throw
180 # in the loose (sid) matches at the end
181 my $msgs = do_get($self, <<"", $opts, $tid, $num);
182 SELECT $cols FROM over WHERE tid = ? AND num > ?
183 ORDER BY $sort_col ASC
185 # do we have room for loose matches? get the most recent ones, first:
186 my $lim = DEFAULT_LIMIT - scalar(@$msgs);
188 $opts->{limit} = $lim;
189 my $loose = do_get($self, <<"", $opts, $tid, $sid, $num);
190 SELECT $cols FROM over WHERE tid != ? AND sid = ? AND num > ?
191 ORDER BY $sort_col DESC
193 # TODO separate strict and loose matches here once --reindex
194 # is fixed to preserve `tid' properly
195 push @$msgs, @$loose;
200 # strict `tid' matches, only, for thread-expanded mbox.gz search results
201 # and future CLI interface
202 # returns true if we have IDs, undef if not
204 my ($self, $ctx) = @_;
205 my $dbh = $self->connect;
207 defined(my $num = $ctx->{ids}->[0]) or return;
208 my ($tid) = $dbh->selectrow_array(<<'', undef, $num);
209 SELECT tid FROM over WHERE num = ?
213 SELECT num FROM over WHERE tid = ? AND num > ?
214 ORDER BY num ASC LIMIT 1000
216 my $xids = $dbh->selectcol_arrayref($sql, undef, $tid,
218 if (scalar(@$xids)) {
219 $ctx->{prev} = $xids->[-1];
220 $ctx->{xids} = $xids;
225 shift @{$ctx->{ids}};
230 my ($self, $opts, $after, $before) = @_;
232 if (defined($before)) {
233 if (defined($after)) {
234 $s = '+num > 0 AND ts >= ? AND ts <= ? ORDER BY ts DESC';
235 @v = ($after, $before);
237 $s = '+num > 0 AND ts <= ? ORDER BY ts DESC';
241 if (defined($after)) {
242 $s = '+num > 0 AND ts >= ? ORDER BY ts ASC';
245 $s = '+num > 0 ORDER BY ts DESC';
248 my $msgs = do_get($self, <<"", $opts, @v);
249 SELECT ts,ds,ddd FROM over WHERE $s
251 return $msgs unless wantarray;
253 my $nr = $self->{dbh}->selectrow_array(<<'');
254 SELECT COUNT(num) FROM over WHERE num > 0
260 my ($self, $num) = @_;
261 # caching $sth ourselves is faster than prepare_cached
262 my $sth = $self->{-get_art} //= $self->connect->prepare(<<'');
263 SELECT num,tid,ds,ts,ddd FROM over WHERE num = ? LIMIT 1
266 my $smsg = $sth->fetchrow_hashref;
267 $smsg ? load_from_row($smsg) : undef;
271 my ($self, $mid, $id, $prev) = @_;
272 my $dbh = $self->connect;
274 unless (defined $$id) {
275 my $sth = $dbh->prepare_cached(<<'', undef, 1);
276 SELECT id FROM msgid WHERE mid = ? LIMIT 1
279 $$id = $sth->fetchrow_array;
280 defined $$id or return;
282 my $sth = $dbh->prepare_cached(<<"", undef, 1);
283 SELECT num FROM id2num WHERE id = ? AND num > ?
284 ORDER BY num ASC LIMIT 1
287 $sth->execute($$id, $$prev);
288 my $num = $sth->fetchrow_array or return;
290 get_art($self, $num);
293 # IMAP search, this is limited by callers to UID_SLICE size (50K)
295 my ($self, $beg, $end, $sql) = @_;
296 my $dbh = $self->connect;
297 my $q = 'SELECT num FROM over WHERE num >= ? AND num <= ?';
299 # This is read-only, anyways; but caller should verify it's
300 # only sending \A[0-9]+\z for ds and ts column ranges
302 $q .= ' ORDER BY num ASC';
303 $dbh->selectcol_arrayref($q, undef, $beg, $end);
308 my $sth = $self->connect->prepare_cached(<<'', undef, 1);
309 SELECT MAX(num) FROM over WHERE num > 0
312 $sth->fetchrow_array // 0;
316 my ($self, $uid_base, $uid_end) = @_;
317 my $sth = $self->connect->prepare_cached(<<'', undef, 1);
318 SELECT COUNT(num) FROM over WHERE num > ? AND num <= ?
320 $sth->execute($uid_base, $uid_end);
321 $sth->fetchrow_array;
326 my $dbh = $self->{dbh} or return;
327 my $f = $dbh->sqlite_db_filename;
328 if (my @st = stat($f)) { # did st_dev, st_ino change?
329 my $st = pack('dd', $st[0], $st[1]);
331 # don't actually reopen, just let {dbh} be recreated later
332 disconnect($self) if $st ne ($self->{st} // $st);
334 warn "W: stat $f: $!\n";