1 # Copyright (C) 2018-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::IMAPTracker;
5 use parent qw(PublicInbox::Lock);
8 use PublicInbox::Config;
10 sub create_tables ($) {
14 CREATE TABLE IF NOT EXISTS imap_last (
15 url VARCHAR PRIMARY KEY NOT NULL,
16 uid_validity INTEGER NOT NULL,
25 my $dbh = DBI->connect("dbi:SQLite:dbname=$dbname", '', '', {
29 sqlite_use_immediate_transaction => 1,
31 $dbh->{sqlite_unicode} = 1;
33 # TRUNCATE reduces I/O compared to the default (DELETE).
34 # Allow and preserve user-overridden WAL, but don't force it.
35 my $jm = $dbh->selectrow_array('PRAGMA journal_mode');
36 $dbh->do('PRAGMA journal_mode = TRUNCATE') if $jm ne 'wal';
43 my ($self, $validity) = @_;
45 if (defined $validity) {
46 $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
47 SELECT uid_validity, uid FROM imap_last WHERE url = ? AND uid_validity = ?
49 $sth->execute($self->{url}, $validity);
51 $sth = $self->{dbh}->prepare_cached(<<'', undef, 1);
52 SELECT uid_validity, uid FROM imap_last WHERE url = ?
54 $sth->execute($self->{url});
59 sub update_last ($$$) {
60 my ($self, $validity, $last_uid) = @_;
61 return unless defined $last_uid;
62 my $sth = $self->{dbh}->prepare_cached(<<'');
63 INSERT OR REPLACE INTO imap_last (url, uid_validity, uid)
67 my $rv = $sth->execute($self->{url}, $validity, $last_uid);
73 my ($class, $url, $dbname) = @_;
75 unless (defined($dbname)) {
76 # original name for compatibility with old setups:
77 $dbname = PublicInbox::Config->config_dir() . '/imap.sqlite3';
79 # use the new XDG-compliant name for new setups:
81 $dbname = ($ENV{XDG_DATA_HOME} //
82 (($ENV{HOME} // '/nonexistent').
84 '/public-inbox/imap.sqlite3';
89 require File::Basename;
90 require PublicInbox::Spawn;
91 File::Path::mkpath(File::Basename::dirname($dbname));
92 open my $fh, '+>>', $dbname or die "failed to open $dbname: $!";
93 PublicInbox::Spawn::nodatacow_fd(fileno($fh));
95 my $self = bless { lock_path => "$dbname.lock", url => $url }, $class;
97 $self->{dbh} = dbh_new($dbname);