1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # fork()-friendly key-value store. Will be used for making
5 # augmenting Maildirs and mboxes less expensive, maybe.
6 # We use flock(2) to avoid SQLite lock problems (busy timeouts, backoff)
7 package PublicInbox::SharedKV;
10 use parent qw(PublicInbox::Lock);
11 use File::Temp qw(tempdir);
13 use PublicInbox::Spawn;
14 use File::Path qw(rmtree make_path);
17 my ($self, $lock) = @_;
19 my $f = $self->{filename};
20 $lock //= $self->lock_for_scope_fast;
21 my $dbh = DBI->connect("dbi:SQLite:dbname=$f", '', '', {
25 sqlite_use_immediate_transaction => 1,
26 # no sqlite_unicode here, this is for binary data
28 my $opt = $self->{opt} // {};
29 $dbh->do('PRAGMA synchronous = OFF') if !$opt->{fsync};
30 $dbh->do('PRAGMA journal_mode = '.
31 ($opt->{journal_mode} // 'WAL'));
33 CREATE TABLE IF NOT EXISTS kv (
34 k VARBINARY PRIMARY KEY NOT NULL,
44 my ($cls, $dir, $base, $opt) = @_;
45 my $self = bless { opt => $opt }, $cls;
46 make_path($dir) if defined($dir) && !-d $dir;
47 $dir //= $self->{"tmp$$.$self"} = tempdir("skv.$$-XXXX", TMPDIR => 1);
49 my $f = $self->{filename} = "$dir/$base.sqlite3";
50 $self->{lock_path} = $opt->{lock_path} // "$dir/$base.flock";
52 PublicInbox::Spawn::nodatacow_dir($dir); # for journal/shm/wal
53 open my $fh, '+>>', $f or die "failed to open $f: $!";
54 PublicInbox::Spawn::nodatacow_fd(fileno($fh));
61 my $lock = $self->lock_for_scope_fast;
62 $self->dbh($lock)->do('CREATE INDEX IF NOT EXISTS idx_v ON kv (v)');
66 my ($self, $key, $val, $lock) = @_;
67 $lock //= $self->lock_for_scope_fast;
68 my $e = $self->{dbh}->prepare_cached(<<'')->execute($key, $val);
69 INSERT OR IGNORE INTO kv (k,v) VALUES (?, ?)
74 # caller calls sth->fetchrow_array
77 my $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
85 my ($self, @pfx) = @_;
86 my $sql = 'SELECT k FROM kv';
87 if (defined $pfx[0]) {
88 $sql .= ' WHERE k LIKE ? ESCAPE ?';
89 my $anywhere = !!$pfx[1];
91 $pfx[0] =~ s/([%_\\])/\\$1/g; # glob chars
93 substr($pfx[0], 0, 0, '%') if $anywhere;
95 @pfx = (); # [0] may've been undef
97 map { $_->[0] } @{$self->dbh->selectall_arrayref($sql, undef, @pfx)};
101 my ($self, $val, $lock) = @_;
102 $lock //= $self->lock_for_scope_fast;
103 $self->{dbh}->prepare_cached(<<'')->execute($val) + 0;
104 DELETE FROM kv WHERE v = ?
109 my ($self, $oldval, $newval, $lock) = @_;
110 $lock //= $self->lock_for_scope_fast;
111 $self->{dbh}->prepare_cached(<<'')->execute($newval, $oldval) + 0;
112 UPDATE kv SET v = ? WHERE v = ?
117 my ($self, $key, $val) = @_;
119 my $e = $self->{dbh}->prepare_cached(<<'')->execute($key, $val);
120 INSERT OR REPLACE INTO kv (k,v) VALUES (?,?)
122 $e == 0 ? undef : $e;
124 $self->{dbh}->prepare_cached(<<'')->execute($key);
125 DELETE FROM kv WHERE k = ?
131 my ($self, $key) = @_;
132 my $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
133 SELECT v FROM kv WHERE k = ?
136 $sth->fetchrow_array;
140 my ($self, $key, $newval, $lock) = @_;
141 $lock //= $self->lock_for_scope_fast;
142 my $oldval = get($self, $key);
143 if (defined $newval) {
144 set($self, $key, $newval);
146 $self->{dbh}->prepare_cached(<<'')->execute($key);
147 DELETE FROM kv WHERE k = ?
155 my $sth = $self->{dbh}->prepare_cached(<<'');
156 SELECT COUNT(k) FROM kv
159 $sth->fetchrow_array;
162 # faster than ->count due to how SQLite works
165 my @n = $self->{dbh}->selectrow_array('SELECT k FROM kv LIMIT 1');
166 scalar(@n) ? 1 : undef;
170 my ($self, $lock) = @_;
171 my $dbh = delete $self->{dbh} or return;
172 $lock //= $self->lock_for_scope_fast; # may be needed for WAL
173 %{$dbh->{CachedKids}} = (); # cleanup prepare_cached
180 my $dir = delete $self->{"tmp$$.$self"} or return;
184 eval { rmtree($dir) };
185 } while ($@ && $!{ENOENT} && $tries++ < 5);
186 warn "error removing $dir: $@" if $@;
187 warn "Took $tries tries to remove $dir\n" if $tries;