]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Over.pm
over+msgmap: do not store filename after DBI->connect
[public-inbox.git] / lib / PublicInbox / Over.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_ database which can be
6 # tweaked/updated over time and rebuilt.
7 package PublicInbox::Over;
8 use strict;
9 use warnings;
10 use DBI;
11 use DBD::SQLite;
12 use PublicInbox::Smsg;
13 use Compress::Zlib qw(uncompress);
14 use constant DEFAULT_LIMIT => 1000;
15
16 sub dbh_new {
17         my ($self, $rw) = @_;
18         my $f = delete $self->{filename};
19         if (!-f $f) { # SQLite defaults mode to 0644, we want 0666
20                 if ($rw) {
21                         open my $fh, '+>>', $f or die "failed to open $f: $!";
22                 } else {
23                         $self->{filename} = $f; # die on stat() below:
24                 }
25         }
26         my (@st, $st, $dbh);
27         my $tries = 0;
28         do {
29                 @st = stat($f) or die "failed to stat $f: $!";
30                 $st = pack('dd', $st[0], $st[1]); # 0: dev, 1: inode
31                 $dbh = DBI->connect("dbi:SQLite:dbname=$f",'','', {
32                         AutoCommit => 1,
33                         RaiseError => 1,
34                         PrintError => 0,
35                         ReadOnly => !$rw,
36                         sqlite_use_immediate_transaction => 1,
37                 });
38                 $self->{st} = $st;
39                 @st = stat($f) or die "failed to stat $f: $!";
40                 $st = pack('dd', $st[0], $st[1]);
41         } while ($st ne $self->{st} && $tries++ < 3);
42         warn "W: $f: .st_dev, .st_ino unstable\n" if $st ne $self->{st};
43         $dbh;
44 }
45
46 sub new {
47         my ($class, $f) = @_;
48         bless { filename => $f }, $class;
49 }
50
51 sub disconnect {
52         my ($self) = @_;
53         if (my $dbh = delete $self->{dbh}) {
54                 $self->{filename} = $dbh->sqlite_db_filename;
55         }
56 }
57
58 sub connect { $_[0]->{dbh} //= $_[0]->dbh_new }
59
60 sub load_from_row ($;$) {
61         my ($smsg, $cull) = @_;
62         bless $smsg, 'PublicInbox::Smsg';
63         if (defined(my $data = delete $smsg->{ddd})) {
64                 $data = uncompress($data);
65                 utf8::decode($data);
66                 PublicInbox::Smsg::load_from_data($smsg, $data);
67
68                 # saves over 600K for 1000+ message threads
69                 PublicInbox::Smsg::psgi_cull($smsg) if $cull;
70         }
71         $smsg
72 }
73
74 sub do_get {
75         my ($self, $sql, $opts, @args) = @_;
76         my $dbh = $self->connect;
77         my $lim = (($opts->{limit} || 0) + 0) || DEFAULT_LIMIT;
78         $sql .= "LIMIT $lim";
79         my $msgs = $dbh->selectall_arrayref($sql, { Slice => {} }, @args);
80         my $cull = $opts->{cull};
81         load_from_row($_, $cull) for @$msgs;
82         $msgs
83 }
84
85 sub query_xover {
86         my ($self, $beg, $end) = @_;
87         do_get($self, <<'', {}, $beg, $end);
88 SELECT num,ts,ds,ddd FROM over WHERE num >= ? AND num <= ?
89 ORDER BY num ASC
90
91 }
92
93 sub query_ts {
94         my ($self, $ts, $prev) = @_;
95         do_get($self, <<'', {}, $ts, $prev);
96 SELECT num,ddd FROM over WHERE ts >= ? AND num > ?
97 ORDER BY num ASC
98
99 }
100
101 sub nothing () { wantarray ? (0, []) : [] };
102
103 sub get_thread {
104         my ($self, $mid, $prev) = @_;
105         my $dbh = $self->connect;
106         my $opts = { cull => 1 };
107
108         my $id = $dbh->selectrow_array(<<'', undef, $mid);
109 SELECT id FROM msgid WHERE mid = ? LIMIT 1
110
111         defined $id or return nothing;
112
113         my $num = $dbh->selectrow_array(<<'', undef, $id);
114 SELECT num FROM id2num WHERE id = ? AND num > 0
115 ORDER BY num ASC LIMIT 1
116
117         defined $num or return nothing;
118
119         my ($tid, $sid) = $dbh->selectrow_array(<<'', undef, $num);
120 SELECT tid,sid FROM over WHERE num = ? LIMIT 1
121
122         defined $tid or return nothing; # $sid may be undef
123
124         my $cond_all = '(tid = ? OR sid = ?) AND num > ?';
125         my $sort_col = 'ds';
126         $num = 0;
127         if ($prev) { # mboxrd stream, only
128                 $num = $prev->{num} || 0;
129                 $sort_col = 'num';
130         }
131
132         my $cols = 'num,ts,ds,ddd';
133         unless (wantarray) {
134                 return do_get($self, <<"", $opts, $tid, $sid, $num);
135 SELECT $cols FROM over WHERE $cond_all
136 ORDER BY $sort_col ASC
137
138         }
139
140         # HTML view always wants an array and never uses $prev,
141         # but the mbox stream never wants an array and always has $prev
142         die '$prev not supported with wantarray' if $prev;
143         my $nr = $dbh->selectrow_array(<<"", undef, $tid, $sid, $num);
144 SELECT COUNT(num) FROM over WHERE $cond_all
145
146         # giant thread, prioritize strict (tid) matches and throw
147         # in the loose (sid) matches at the end
148         my $msgs = do_get($self, <<"", $opts, $tid, $num);
149 SELECT $cols FROM over WHERE tid = ? AND num > ?
150 ORDER BY $sort_col ASC
151
152         # do we have room for loose matches? get the most recent ones, first:
153         my $lim = DEFAULT_LIMIT - scalar(@$msgs);
154         if ($lim > 0) {
155                 $opts->{limit} = $lim;
156                 my $loose = do_get($self, <<"", $opts, $tid, $sid, $num);
157 SELECT $cols FROM over WHERE tid != ? AND sid = ? AND num > ?
158 ORDER BY $sort_col DESC
159
160                 # TODO separate strict and loose matches here once --reindex
161                 # is fixed to preserve `tid' properly
162                 push @$msgs, @$loose;
163         }
164         ($nr, $msgs);
165 }
166
167 sub recent {
168         my ($self, $opts, $after, $before) = @_;
169         my ($s, @v);
170         if (defined($before)) {
171                 if (defined($after)) {
172                         $s = '+num > 0 AND ts >= ? AND ts <= ? ORDER BY ts DESC';
173                         @v = ($after, $before);
174                 } else {
175                         $s = '+num > 0 AND ts <= ? ORDER BY ts DESC';
176                         @v = ($before);
177                 }
178         } else {
179                 if (defined($after)) {
180                         $s = '+num > 0 AND ts >= ? ORDER BY ts ASC';
181                         @v = ($after);
182                 } else {
183                         $s = '+num > 0 ORDER BY ts DESC';
184                 }
185         }
186         my $msgs = do_get($self, <<"", $opts, @v);
187 SELECT ts,ds,ddd FROM over WHERE $s
188
189         return $msgs unless wantarray;
190
191         my $nr = $self->{dbh}->selectrow_array(<<'');
192 SELECT COUNT(num) FROM over WHERE num > 0
193
194         ($nr, $msgs);
195 }
196
197 sub get_art {
198         my ($self, $num) = @_;
199         my $dbh = $self->connect;
200         my $sth = $dbh->prepare_cached(<<'', undef, 1);
201 SELECT num,ds,ts,ddd FROM over WHERE num = ? LIMIT 1
202
203         $sth->execute($num);
204         my $smsg = $sth->fetchrow_hashref;
205         $smsg ? load_from_row($smsg) : undef;
206 }
207
208 sub next_by_mid {
209         my ($self, $mid, $id, $prev) = @_;
210         my $dbh = $self->connect;
211
212         unless (defined $$id) {
213                 my $sth = $dbh->prepare_cached(<<'', undef, 1);
214         SELECT id FROM msgid WHERE mid = ? LIMIT 1
215
216                 $sth->execute($mid);
217                 $$id = $sth->fetchrow_array;
218                 defined $$id or return;
219         }
220         my $sth = $dbh->prepare_cached(<<"", undef, 1);
221 SELECT num FROM id2num WHERE id = ? AND num > ?
222 ORDER BY num ASC LIMIT 1
223
224         $$prev ||= 0;
225         $sth->execute($$id, $$prev);
226         my $num = $sth->fetchrow_array or return;
227         $$prev = $num;
228
229         $sth = $dbh->prepare_cached(<<"", undef, 1);
230 SELECT num,ts,ds,ddd FROM over WHERE num = ? LIMIT 1
231
232         $sth->execute($num);
233         my $smsg = $sth->fetchrow_hashref or return;
234         load_from_row($smsg);
235 }
236
237 # IMAP search, this is limited by callers to UID_SLICE size (50K)
238 sub uid_range {
239         my ($self, $beg, $end, $sql) = @_;
240         my $dbh = $self->connect;
241         my $q = 'SELECT num FROM over WHERE num >= ? AND num <= ?';
242
243         # This is read-only, anyways; but caller should verify it's
244         # only sending \A[0-9]+\z for ds and ts column ranges
245         $q .= $$sql if $sql;
246         $q .= ' ORDER BY num ASC';
247         $dbh->selectcol_arrayref($q, undef, $beg, $end);
248 }
249
250 sub max {
251         my ($self) = @_;
252         my $sth = $self->connect->prepare_cached(<<'', undef, 1);
253 SELECT MAX(num) FROM over WHERE num > 0
254
255         $sth->execute;
256         $sth->fetchrow_array // 0;
257 }
258
259 sub imap_exists {
260         my ($self, $uid_base, $uid_end) = @_;
261         my $sth = $self->connect->prepare_cached(<<'', undef, 1);
262 SELECT COUNT(num) FROM over WHERE num > ? AND num <= ?
263
264         $sth->execute($uid_base, $uid_end);
265         $sth->fetchrow_array;
266 }
267
268 sub check_inodes {
269         my ($self) = @_;
270         my $dbh = $self->{dbh} or return;
271         my $f = $dbh->sqlite_db_filename;
272         if (my @st = stat($f)) { # did st_dev, st_ino change?
273                 my $st = pack('dd', $st[0], $st[1]);
274
275                 # don't actually reopen, just let {dbh} be recreated later
276                 if ($st ne ($self->{st} // $st)) {
277                         delete($self->{dbh});
278                         $self->{filename} = $f;
279                 }
280         } else {
281                 warn "W: stat $f: $!\n";
282         }
283 }
284
285 1;