]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Msgmap.pm
msgmap: use "CREATE TABLE IF NOT EXISTS"
[public-inbox.git] / lib / PublicInbox / Msgmap.pm
1 # Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # bidirectional Message-ID <-> Article Number mapping for the NNTP
5 # and web interfaces.  This is required for implementing stable article
6 # numbers for NNTP and allows prefix lookups for partial Message-IDs
7 # in case URLs get truncated from copy-n-paste errors by users.
8 #
9 # This is maintained by ::SearchIdx
10 package PublicInbox::Msgmap;
11 use strict;
12 use DBI;
13 use DBD::SQLite;
14 use PublicInbox::Over;
15 use PublicInbox::Spawn;
16
17 sub new {
18         my ($class, $git_dir, $writable) = @_;
19         my $d = "$git_dir/public-inbox";
20         if ($writable && !-d $d && !mkdir $d) {
21                 my $err = $!;
22                 -d $d or die "$d not created: $err";
23         }
24         new_file($class, "$d/msgmap.sqlite3", $writable);
25 }
26
27 sub new_file {
28         my ($class, $f, $rw) = @_;
29         return if !$rw && !-r $f;
30
31         my $self = bless { filename => $f }, $class;
32         my $dbh = $self->{dbh} = PublicInbox::Over::dbh_new($self, $rw);
33         if ($rw) {
34                 # TRUNCATE reduces I/O compared to the default (DELETE)
35                 $dbh->do('PRAGMA journal_mode = TRUNCATE');
36
37                 $dbh->begin_work;
38                 create_tables($dbh);
39                 $self->created_at(time) unless $self->created_at;
40
41                 my $max = $self->max // 0;
42                 $self->num_highwater($max);
43                 $dbh->commit;
44         }
45         $self;
46 }
47
48 # used to keep track of used numeric mappings for v2 reindex
49 sub tmp_clone {
50         my ($self, $dir) = @_;
51         require File::Temp;
52         my $tmp = "mm_tmp-$$-XXXXXX";
53         my ($fh, $fn) = File::Temp::tempfile($tmp, EXLOCK => 0, DIR => $dir);
54         PublicInbox::Spawn::nodatacow_fd(fileno($fh));
55         $self->{dbh}->sqlite_backup_to_file($fn);
56         $tmp = ref($self)->new_file($fn, 2);
57         $tmp->{dbh}->do('PRAGMA journal_mode = MEMORY');
58         $tmp->{pid} = $$;
59         $tmp;
60 }
61
62 # n.b. invoked directly by scripts/xhdr-num2mid
63 sub meta_accessor {
64         my ($self, $key, $value) = @_;
65
66         my $sql = 'SELECT val FROM meta WHERE key = ? LIMIT 1';
67         my $dbh = $self->{dbh};
68         my $prev;
69         defined $value or return $dbh->selectrow_array($sql, undef, $key);
70
71         $prev = $dbh->selectrow_array($sql, undef, $key);
72
73         if (defined $prev) {
74                 $sql = 'UPDATE meta SET val = ? WHERE key = ?';
75                 $dbh->do($sql, undef, $value, $key);
76         } else {
77                 $sql = 'INSERT INTO meta (key,val) VALUES (?,?)';
78                 $dbh->do($sql, undef, $key, $value);
79         }
80         $prev;
81 }
82
83 sub last_commit {
84         my ($self, $commit) = @_;
85         $self->meta_accessor('last_commit', $commit);
86 }
87
88 # v2 uses this to keep track of how up-to-date Xapian is
89 # old versions may be automatically GC'ed away in the future,
90 # but it's a trivial amount of storage.
91 sub last_commit_xap {
92         my ($self, $version, $i, $commit) = @_;
93         $self->meta_accessor("last_xap$version-$i", $commit);
94 }
95
96 sub created_at {
97         my ($self, $second) = @_;
98         $self->meta_accessor('created_at', $second);
99 }
100
101 sub num_highwater {
102         my ($self, $num) = @_;
103         my $high = $self->{num_highwater} ||=
104             $self->meta_accessor('num_highwater');
105         if (defined($num) && (!defined($high) || ($num > $high))) {
106                 $self->{num_highwater} = $num;
107                 $self->meta_accessor('num_highwater', $num);
108         }
109         $self->{num_highwater};
110 }
111
112 sub mid_insert {
113         my ($self, $mid) = @_;
114         my $dbh = $self->{dbh};
115         my $sth = $dbh->prepare_cached(<<'');
116 INSERT INTO msgmap (mid) VALUES (?)
117
118         return unless eval { $sth->execute($mid) };
119         my $num = $dbh->last_insert_id(undef, undef, 'msgmap', 'num');
120         $self->num_highwater($num) if defined($num);
121         $num;
122 }
123
124 sub mid_for {
125         my ($self, $num) = @_;
126         my $dbh = $self->{dbh};
127         my $sth = $self->{mid_for} ||=
128                 $dbh->prepare('SELECT mid FROM msgmap WHERE num = ? LIMIT 1');
129         $sth->bind_param(1, $num);
130         $sth->execute;
131         $sth->fetchrow_array;
132 }
133
134 sub num_for {
135         my ($self, $mid) = @_;
136         my $dbh = $self->{dbh};
137         my $sth = $self->{num_for} ||=
138                 $dbh->prepare('SELECT num FROM msgmap WHERE mid = ? LIMIT 1');
139         $sth->bind_param(1, $mid);
140         $sth->execute;
141         $sth->fetchrow_array;
142 }
143
144 sub max {
145         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MAX(num) FROM msgmap',
146                                                 undef, 1);
147         $sth->execute;
148         $sth->fetchrow_array;
149 }
150
151 sub minmax {
152         # breaking MIN and MAX into separate queries speeds up from 250ms
153         # to around 700us with 2.7million messages.
154         my $sth = $_[0]->{dbh}->prepare_cached('SELECT MIN(num) FROM msgmap',
155                                                 undef, 1);
156         $sth->execute;
157         ($sth->fetchrow_array, max($_[0]));
158 }
159
160 sub mid_delete {
161         my ($self, $mid) = @_;
162         my $dbh = $self->{dbh};
163         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE mid = ?');
164         $sth->bind_param(1, $mid);
165         $sth->execute;
166 }
167
168 sub num_delete {
169         my ($self, $num) = @_;
170         my $dbh = $self->{dbh};
171         my $sth = $dbh->prepare('DELETE FROM msgmap WHERE num = ?');
172         $sth->bind_param(1, $num);
173         $sth->execute;
174 }
175
176 sub create_tables {
177         my ($dbh) = @_;
178
179         $dbh->do(<<'');
180 CREATE TABLE IF NOT EXISTS msgmap (
181         num INTEGER PRIMARY KEY AUTOINCREMENT,
182         mid VARCHAR(1000) NOT NULL,
183         UNIQUE (mid)
184 )
185
186         $dbh->do(<<'');
187 CREATE TABLE IF NOT EXISTS meta (
188         key VARCHAR(32) PRIMARY KEY,
189         val VARCHAR(255) NOT NULL
190 )
191
192 }
193
194 # used by NNTP.pm
195 sub ids_after {
196         my ($self, $num) = @_;
197         my $ids = $self->{dbh}->selectcol_arrayref(<<'', undef, $$num);
198 SELECT num FROM msgmap WHERE num > ?
199 ORDER BY num ASC LIMIT 1000
200
201         $$num = $ids->[-1] if @$ids;
202         $ids;
203 }
204
205 sub msg_range {
206         my ($self, $beg, $end, $cols) = @_;
207         $cols //= 'num,mid';
208         my $dbh = $self->{dbh};
209         my $attr = { Columns => [] };
210         my $mids = $dbh->selectall_arrayref(<<"", $attr, $$beg, $end);
211 SELECT $cols FROM msgmap WHERE num >= ? AND num <= ?
212 ORDER BY num ASC LIMIT 1000
213
214         $$beg = $mids->[-1]->[0] + 1 if @$mids;
215         $mids
216 }
217
218 # only used for mapping external serial numbers (e.g. articles from gmane)
219 # see scripts/xhdr-num2mid or PublicInbox::Filter::RubyLang for usage
220 sub mid_set {
221         my ($self, $num, $mid) = @_;
222         my $sth = $self->{mid_set} ||= do {
223                 $self->{dbh}->prepare(
224                         'INSERT OR IGNORE INTO msgmap (num,mid) VALUES (?,?)');
225         };
226         my $result = $sth->execute($num, $mid);
227         $self->num_highwater($num) if (defined($result) && $result == 1);
228         $result;
229 }
230
231 sub DESTROY {
232         my ($self) = @_;
233         my $dbh = $self->{dbh} or return;
234         if (($self->{pid} // 0) == $$) {
235                 my $f = $dbh->sqlite_db_filename;
236                 unlink $f or warn "failed to unlink $f: $!\n";
237         }
238 }
239
240 sub atfork_parent {
241         my ($self) = @_;
242         $self->{pid} or die 'BUG: not a temporary clone';
243         $self->{dbh} and die 'BUG: tmp_clone dbh not prepared for parent';
244         defined($self->{filename}) or die 'BUG: {filename} not defined';
245         $self->{dbh} = PublicInbox::Over::dbh_new($self, 2);
246         $self->{dbh}->do('PRAGMA journal_mode = MEMORY');
247 }
248
249 sub atfork_prepare {
250         my ($self) = @_;
251         my $pid = $self->{pid} or die 'BUG: not a temporary clone';
252         $pid == $$ or die "BUG: atfork_prepare not called by $pid";
253         my $dbh = $self->{dbh} or die 'BUG: temporary clone not open';
254
255         # must clobber prepared statements
256         %$self = (filename => $dbh->sqlite_db_filename, pid => $pid);
257 }
258
259 sub skip_artnum {
260         my ($self, $skip_artnum) = @_;
261         return meta_accessor($self, 'skip_artnum') if !defined($skip_artnum);
262
263         my $cur = num_highwater($self) // 0;
264         if ($skip_artnum < $cur) {
265                 die "E: current article number $cur ",
266                         "exceeds --skip-artnum=$skip_artnum\n";
267         } else {
268                 my $ok;
269                 for (1..10) {
270                         my $mid = 'skip'.rand.'@'.rand.'.example.com';
271                         $ok = mid_set($self, $skip_artnum, $mid);
272                         if ($ok) {
273                                 mid_delete($self, $mid);
274                                 last;
275                         }
276                 }
277                 $ok or die '--skip-artnum failed';
278
279                 # in the future, the indexer may use this value for
280                 # new messages in old epochs
281                 meta_accessor($self, 'skip_artnum', $skip_artnum);
282         }
283 }
284
285 sub check_inodes {
286         my ($self) = @_;
287         # no filename if in-:memory:
288         my $f = $self->{dbh}->sqlite_db_filename // return;
289         if (my @st = stat($f)) { # did st_dev, st_ino change?
290                 my $st = pack('dd', $st[0], $st[1]);
291                 if ($st ne ($self->{st} // $st)) {
292                         my $tmp = eval { ref($self)->new_file($f) };
293                         if ($@) {
294                                 warn "E: DBI->connect($f): $@\n";
295                         } else {
296                                 %$self = %$tmp;
297                         }
298                 }
299         } else {
300                 warn "W: stat $f: $!\n";
301         }
302 }
303
304 1;