store

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store is maild's SQLite database: migrations, the single writer, the durable event log and the queries (docs/design/storage.md).

Reads go through DB methods and may run concurrently. Every write runs in DB.Tx, which serializes writers, records the events the transaction emits and hands them to OnCommit after commit, in commit order.

Index

Constants

View Source
const (
	DefaultPreviewLines = 2
	MaxPreviewLines     = 5
)

The message list shows DefaultPreviewLines lines of a message's preview unless the user chose another number, at most MaxPreviewLines.

View Source
const (
	OpRelinkPeople = "RelinkPeople"
	OpObjectByHref = "ObjectByHref"
	OpObjectRaws   = "ObjectRaws"
)

The operations Observe names.

View Source
const FlagColors = 7

FlagColors is how many flag colors there are, and so flag names.

View Source
const MaxSnippets = 200

MaxSnippets is how many snippets the store keeps (docs/design/send.md, Snippets).

View Source
const SubjectWindow = 7 * 24 * time.Hour

SubjectWindow is how far back a reply without references may join a thread by subject alone (docs/design/sync.md, threading).

View Source
const TimeFormat = "2006-01-02T15:04:05.000Z"

TimeFormat is how times are stored: UTC, fixed width, lexically sortable.

Variables

View Source
var (
	// ErrNotFound means the row does not exist.
	ErrNotFound = errors.New("store: not found")
	// ErrConflict means a uniqueness rule rejected the write.
	ErrConflict = errors.New("store: conflict")
	// ErrMigrate matches every error of Open's migrations: the schema
	// could not be brought up to this maild's, or the database is newer.
	ErrMigrate = errors.New("store: migrate")
)
View Source
var ErrCondition = errors.New("invalid condition")

ErrCondition reports a condition maild cannot compile; the error names it, for invalidParams.

View Source
var ErrTooManySnippets = errors.New("store: too many snippets")

ErrTooManySnippets is CreateSnippet's error when MaxSnippets are kept.

Functions

func CheckConditions

func CheckConditions(c api.Conditions) error

CheckConditions reports the first condition CompileConditions would refuse, wrapping ErrCondition. Stored conditions are checked first, so they always compile.

func FormatTime

func FormatTime(t time.Time) string

FormatTime renders t in TimeFormat.

func IsForeignKeyViolation

func IsForeignKeyViolation(err error) bool

IsForeignKeyViolation reports whether err is SQLite's foreign key constraint failure: a row names a parent that does not exist.

func IsUniqueViolation

func IsUniqueViolation(err error) bool

IsUniqueViolation reports whether err is a SQLite UNIQUE or PRIMARY KEY constraint failure; callers map it to ErrConflict.

func KnownSchema

func KnownSchema() (int, error)

KnownSchema is the schema version this build migrates a database to.

func NewStoreID added in v0.4.0

func NewStoreID(ctx context.Context, path string) (string, error)

NewStoreID gives the database at path a new store id: 32 hex characters, drawn at random and saved with INSERT OR REPLACE in store_info (ADR-0046), so that two stores never share keyring items. It returns "" and no error when the database has no store_info table, a schema from before migration 19: maild makes an id after it migrates. path must be a copy that no maild uses: it is not migrated, and no -wal or -shm file stays beside it.

func ParseTime

func ParseTime(s string) (time.Time, error)

ParseTime parses a TimeFormat value.

func Pristine added in v0.4.0

func Pristine(ctx context.Context, path string) (ok bool, reason string, err error)

Pristine reports whether the store at path holds nothing that an import would mix with: no account, no message, no draft and nothing in the outbox. A database that does not exist is pristine, and stays absent (the first maild makes it). reason says what a store that is not pristine holds. The database is opened read-only: not migrated, and neither it nor the committed data of its -wal file changes. SQLite may still update the -shm file, which is only an index of the -wal, rebuilt from it.

func UnsubscribeKey

func UnsubscribeKey(listID string, messageID int64) string

UnsubscribeKey is how an unsubscribe is remembered: by List-Id, else by message (ADR-0027).

Types

type Account

type Account struct {
	ID          int64
	Kind        api.AccountKind
	Email       string
	DisplayName string
	Auth        api.AuthKind
	IMAP        ServerConfig
	SMTP        ServerConfig
	CreatedAt   time.Time
	ReadOnly    bool // maild makes no changes on the server
	Notify      bool // new inbox mail shows a desktop notification
	SyncDays    int  // keep the messages of the last SyncDays days; 0 keeps all (ADR-0016)
	// EraseTrashDays and EraseJunkDays are how long a message stays in the
	// account's trash or junk mailbox before maild erases it: 0 (Never), 1,
	// 7 or 30 (ADR-0051).
	EraseTrashDays int
	EraseJunkDays  int
	NeedsReauth    bool // the server or OAuth provider refused the stored credential
	// GrantedScopes are the OAuth scopes the account's grant covers,
	// space-separated; "" for password accounts.
	GrantedScopes string
	// SMTPMaxSize is the server's SIZE at the last submission, in bytes;
	// 0 means unknown or no announced limit. SMTP settings changes reset it
	// (docs/design/send.md, Attachments).
	SMTPMaxSize int64
}

Account is an accounts row.

func (Account) HasScope

func (a Account) HasScope(scope string) bool

HasScope reports whether the account's grant covers scope.

type AccountUpdate

type AccountUpdate struct {
	DisplayName *string
	IMAP        *ServerConfig
	SMTP        *ServerConfig
	ReadOnly    *bool
	Notify      *bool
	SyncDays    *int
	// EraseTrashDays and EraseJunkDays: 0 (Never), 1, 7 or 30 (ADR-0051).
	EraseTrashDays *int
	EraseJunkDays  *int
}

AccountUpdate changes the non-nil fields of an account.

type Address

type Address struct {
	Name string `json:"name"`
	Addr string `json:"addr"`
}

Address is one mailbox address.

type AlarmKey

type AlarmKey struct {
	CollectionID int64
	UID          string
	// RecurrenceID is the occurrence's ("" for a single event).
	RecurrenceID string
	TriggerAt    time.Time
}

AlarmKey names one alarm of one occurrence: a reminders row's key. It survives resyncs, and an event moved to a new time gets a new trigger.

type AlarmRow

type AlarmRow struct {
	Action     string // display or audio
	Offset     *time.Duration
	RelatedEnd bool
	At         *time.Time
}

AlarmRow is an alarms row: relative (Offset set) or absolute (At set).

type AttendeeRow

type AttendeeRow struct {
	Email    string
	Name     string
	Role     string // chair, required, optional, none
	PartStat string // needsaction, accepted, declined, tentative, delegated
}

AttendeeRow is an event_attendees row.

type BlockedSender

type BlockedSender struct {
	Address string // lowercased
	Name    string // the name last seen with it in mail, else the one stored when blocked
	At      time.Time
}

BlockedSender is one blocked address (ADR-0028).

type Collection

type Collection struct {
	ID          int64
	AccountID   int64
	Kind        api.CollectionKind
	Href        string // the collection's path, or the Google list's ID
	Name        string
	Description string
	Color       string   // #rrggbb, or ""
	Components  []string // calendars: VEVENT, VTODO; stored comma-separated
	ReadOnly    bool
	Enabled     bool
	IsDefault   bool
	Position    int
	SyncToken   string
	CTag        string
	SyncedAt    *time.Time
}

Collection is a collections row: an address book, calendar or Google Tasks list.

type CollectionFilter

type CollectionFilter struct {
	AccountID   int64
	Kind        api.CollectionKind
	EnabledOnly bool
}

CollectionFilter selects collections; zero fields match every one.

type ContactEmail

type ContactEmail struct {
	Email string
	Label string
}

ContactEmail is one of a contact's email addresses.

type ContactIndex

type ContactIndex struct {
	DisplayName  string
	SortKey      string
	GivenName    string
	FamilyName   string
	Organization string
	Emails       []ContactEmail
	Photo        []byte
	PhotoType    string
}

ContactIndex is what the contacts and contact_emails tables hold for one vCard (internal/vcardx builds it).

type DB

type DB struct {

	// Now is the clock for stored timestamps; tests replace it.
	Now func() time.Time
	// OnCommit receives each committed transaction's events, in commit
	// order, while the write lock is held. It must not block.
	OnCommit func([]api.EventEnvelope)
	// Observe, when set, receives the name of each costly call that a sync
	// pass must not repeat (OpRelinkPeople, OpObjectByHref, OpObjectRaws)
	// as it starts, so that tests can count them. It must not block.
	Observe func(op string)
	// contains filtered or unexported fields
}

DB is the maild database.

func Open

func Open(ctx context.Context, path string) (*DB, error)

Open opens or creates the database at path and applies pending migrations. path must not live on a network or virtiofs share: WAL needs shared memory.

func (*DB) ActiveReminders

func (d *DB) ActiveReminders(ctx context.Context, now time.Time) ([]ReminderRow, error)

ActiveReminders returns the fired reminders to show at now.

func (*DB) AlarmsDue

func (d *DB) AlarmsDue(ctx context.Context, since, until time.Time, local *time.Location) ([]AlarmKey, error)

AlarmsDue returns the alarms of shown occurrences whose trigger is in (since, until] and that have not fired, by trigger.

func (*DB) BlockedAmong

func (d *DB) BlockedAmong(ctx context.Context, ids []int64) ([]int64, error)

BlockedAmong returns those of ids whose sender is blocked, ascending.

func (*DB) BlockedSenders

func (d *DB) BlockedSenders(ctx context.Context) ([]BlockedSender, error)

BlockedSenders returns every blocked sender by address.

func (*DB) ChangesSince

func (d *DB) ChangesSince(ctx context.Context, seq int64) ([]api.EventEnvelope, error)

ChangesSince returns the retained durable events after seq, in order.

func (*DB) Close

func (d *DB) Close() error

Close closes the database.

func (*DB) Collections

func (d *DB) Collections(ctx context.Context, f CollectionFilter) ([]Collection, error)

Collections returns matching collections ordered by account, position and ID.

func (*DB) Contact

func (d *DB) Contact(ctx context.Context, objectID int64) (ContactIndex, error)

Contact returns the stored fields and emails in position order, or ErrNotFound.

func (*DB) ContactsIn

func (d *DB) ContactsIn(ctx context.Context, collectionID int64) (map[int64]bool, error)

ContactsIn returns the object IDs of a collection's contacts.

func (*DB) CountView

func (d *DB) CountView(ctx context.Context, f ViewFilter) (total, unread int, err error)

CountView counts the messages f lists, and the unread ones among them; messages, not threads (Threads is ignored).

func (*DB) DefaultIdentity

func (d *DB) DefaultIdentity(ctx context.Context, accountID int64) (Identity, error)

DefaultIdentity returns an account's default identity, or its first one when none is marked default; an account without identities wraps ErrNotFound.

func (*DB) DraftByMessageID

func (d *DB) DraftByMessageID(ctx context.Context, accountID int64, msgid string) (Draft, error)

DraftByMessageID returns the account's draft with that Message-ID; a missing one wraps ErrNotFound.

func (*DB) DraftsToSave

func (d *DB) DraftsToSave(ctx context.Context, accountID int64, quietBefore time.Time) ([]Draft, error)

DraftsToSave lists the account's drafts (every account when accountID is 0) whose updated_at is at or before quietBefore and whose server copy is missing or older than the content, oldest updated_at first, then lower ID, each with its attachments.

func (*DB) DueMessageReminders

func (d *DB) DueMessageReminders(ctx context.Context, now time.Time) ([]MessageReminder, error)

DueMessageReminders returns the reminders due by now, oldest first.

func (*DB) DueOps

func (d *DB) DueOps(ctx context.Context, accountID int64, now time.Time) ([]Op, error)

DueOps returns an account's queued actions due by now, oldest first.

func (*DB) DueOutbox

func (d *DB) DueOutbox(ctx context.Context, accountID int64, now time.Time) ([]OutboxItem, error)

DueOutbox lists the account's queued messages with send_at at or before now (every account when accountID is 0), by send_at, then ID.

func (*DB) DuePIMOps

func (d *DB) DuePIMOps(ctx context.Context, accountID int64, now time.Time) ([]PIMOp, error)

DuePIMOps returns an account's queued changes that are due at now, oldest first.

func (*DB) Event

func (d *DB) Event(ctx context.Context, id int64) (EventRow, error)

Event returns one event with its attendees, alarms and calendar.

func (*DB) EventTexts added in v0.8.0

func (d *DB) EventTexts(ctx context.Context, f EventsFilter) (map[int64]string, error)

EventTexts returns, by event ID, the text a search reads: the event's summary, location, description, organizer and attendees (names and addresses), one to a line.

func (*DB) Events

func (d *DB) Events(ctx context.Context, f EventsFilter) ([]EventRow, error)

Events returns events without their attendees and alarms, ordered by object and event ID.

func (*DB) EventsByUID

func (d *DB) EventsByUID(ctx context.Context, accountID int64, uid string) ([]EventRow, error)

EventsByUID returns events with uid in accountID's calendars, enabled or not, ordered by ID, without attendees and alarms.

func (*DB) FilterIDs

func (d *DB) FilterIDs(ctx context.Context, f ViewFilter, ids []int64) ([]int64, error)

FilterIDs returns those of ids, ascending, that f lists (Threads and Keep aside): what a smart mailbox or a scope takes of new mail.

func (*DB) GetAccount

func (d *DB) GetAccount(ctx context.Context, id int64) (Account, error)

GetAccount returns one account, or ErrNotFound.

func (*DB) GetCollection

func (d *DB) GetCollection(ctx context.Context, id int64) (Collection, error)

GetCollection returns one collection, or ErrNotFound.

func (*DB) GetDraft

func (d *DB) GetDraft(ctx context.Context, id int64) (Draft, error)

GetDraft returns one draft with its attachments in insertion order (by ID), nil attachments when there are none. A missing draft is an error wrapping ErrNotFound.

func (*DB) GetIdentity

func (d *DB) GetIdentity(ctx context.Context, id int64) (Identity, error)

GetIdentity returns one identity; a missing one wraps ErrNotFound.

func (*DB) GetMailbox

func (d *DB) GetMailbox(ctx context.Context, id int64) (Mailbox, error)

GetMailbox returns one mailbox with its counts, or ErrNotFound.

func (*DB) GetMessage

func (d *DB) GetMessage(ctx context.Context, id int64) (MessageDetail, error)

GetMessage returns one message's details: its summary plus its address lists (nil when empty), header identifiers, list headers, blob ID ("" when NULL) and parts ordered by path (nil when none). A missing row is ErrNotFound.

func (*DB) GetMessages added in v0.8.0

func (d *DB) GetMessages(ctx context.Context, ids []int64) ([]MessageDetail, error)

GetMessages returns the details of ids in the order given, as GetMessage gives them, skipping IDs that do not exist. It runs 3 queries whatever the number of IDs: the messages' rows, their mailbox IDs and their parts. The IDs go in as 1 JSON array (json_each), so their number never meets SQLite's limit on bound variables. No IDs returns an empty slice without querying.

func (*DB) GetObject

func (d *DB) GetObject(ctx context.Context, id int64) (Object, error)

GetObject returns one object, or ErrNotFound.

func (*DB) GetOutbox

func (d *DB) GetOutbox(ctx context.Context, id int64) (OutboxItem, error)

GetOutbox returns one outbox message. A missing message is an error wrapping ErrNotFound.

func (*DB) GmailThreadMessage

func (d *DB) GmailThreadMessage(ctx context.Context, accountID, gmThrID int64) (int64, error)

GmailThreadMessage returns the newest stored message of an account's Gmail thread, for a task made from mail; ErrNotFound when none is stored.

func (*DB) HasMessageIn

func (d *DB) HasMessageIn(ctx context.Context, mailboxID int64, msgid string) (bool, error)

HasMessageIn reports whether a mailbox holds a message with that Message-ID (without angle brackets).

func (*DB) HasQueuedOps

func (d *DB) HasQueuedOps(ctx context.Context, accountID int64) (bool, error)

HasQueuedOps reports whether an account has offline actions not yet replayed or failed.

func (*DB) InboxUnread added in v0.5.0

func (d *DB) InboxUnread(ctx context.Context) (int, error)

InboxUnread is the unread messages in every inbox: the app's sidebar Inboxes count, and the badge maild reports to lodge (lodge ADR-0020). It is CountView with ViewFilter{Role: "inbox"}'s unread value.

func (*DB) InstanceWindow

func (d *DB) InstanceWindow(ctx context.Context) (from, to time.Time, ok bool, err error)

InstanceWindow returns the dates the instances cover.

func (*DB) LatestSeq

func (d *DB) LatestSeq(ctx context.Context) (int64, error)

LatestSeq is the highest durable sequence number ever assigned, or 0. It survives pruning because it reads AUTOINCREMENT's counter.

func (*DB) ListAccounts

func (d *DB) ListAccounts(ctx context.Context) ([]Account, error)

ListAccounts returns every account ordered by ID; none is an empty slice.

func (*DB) ListDrafts

func (d *DB) ListDrafts(ctx context.Context, accountID int64) ([]Draft, error)

ListDrafts lists the drafts of an account (every account when accountID is 0), newest updated_at first, then higher ID first, each with its attachments.

func (*DB) ListIdentities

func (d *DB) ListIdentities(ctx context.Context, accountID int64) ([]Identity, error)

ListIdentities lists an account's identities (every account's when accountID is 0), by account, the default first, then by ID.

func (*DB) ListMailboxes

func (d *DB) ListMailboxes(ctx context.Context, accountID int64) ([]Mailbox, error)

ListMailboxes returns mailboxes ordered by account, role (inbox first, user folders last) and path. accountID 0 means every account.

func (*DB) ListOutbox

func (d *DB) ListOutbox(ctx context.Context, accountID int64) ([]OutboxItem, error)

ListOutbox lists the unsent messages (state other than sent) of an account (every account when accountID is 0), by ID.

func (*DB) LocalCopies

func (d *DB) LocalCopies(ctx context.Context, mailboxID int64) ([]LocalCopy, error)

LocalCopies returns every stored message of a mailbox that has a UID, in UID order.

func (*DB) MailboxByID added in v0.8.0

func (d *DB) MailboxByID(ctx context.Context, accountID, id int64) (Mailbox, error)

MailboxByID returns 1 mailbox of an account without its counts (Total and Unread are 0): it reads 1 row, where ListMailboxes counts the messages of every mailbox. A mailbox that is missing, or that belongs to another account, wraps ErrNotFound.

func (*DB) MailboxByRole

func (d *DB) MailboxByRole(ctx context.Context, accountID int64, role api.MailboxRole) (Mailbox, error)

MailboxByRole returns the account's first mailbox with a role; a missing one wraps ErrNotFound.

func (*DB) MailboxSyncState

func (d *DB) MailboxSyncState(ctx context.Context, mailboxID int64) (SyncState, bool, error)

MailboxSyncState returns a mailbox's stored sync state, with ok false when the mailbox has never been synced (no UIDVALIDITY yet). An unknown mailbox returns ErrNotFound. Task T-0012 implements it.

func (*DB) MailboxUIDs

func (d *DB) MailboxUIDs(ctx context.Context, mailboxID int64) ([]uint32, error)

MailboxUIDs returns the UIDs stored for mailboxID in ascending order; none is an empty slice. Task T-0013 implements it.

func (*DB) MatchingIDs

func (d *DB) MatchingIDs(ctx context.Context, c api.Conditions, ids []int64, loc *time.Location) ([]int64, error)

MatchingIDs returns those of ids, ascending, that c matches as of the store's clock in loc: rules over waiting mail, the notification scope.

func (*DB) MessageAtUID

func (d *DB) MessageAtUID(ctx context.Context, mailboxID int64, uid uint32) (id int64, ok bool, err error)

MessageAtUID returns the ID of the message a mailbox holds at a UID; ok is false when there is none.

func (*DB) MessageBody added in v0.8.0

func (d *DB) MessageBody(ctx context.Context, id int64) (MessageBody, error)

MessageBody returns one message's body blobs and subject in one row read, where GetMessage takes three queries. A missing row is ErrNotFound.

func (*DB) MessageLocation

func (d *DB) MessageLocation(ctx context.Context, id int64) (Location, error)

MessageLocation returns where a message can be fetched from: the membership with a non-NULL uid and the lowest mailbox ID, joined to its mailbox path. None is ErrNotFound.

func (*DB) MessagesByMessageID

func (d *DB) MessagesByMessageID(ctx context.Context, msgid string) ([]MessageCopy, error)

MessagesByMessageID lists the stored messages whose Message-ID header, without angle brackets, is msgid, in the order they were stored.

func (*DB) MessagesWithAddress

func (d *DB) MessagesWithAddress(ctx context.Context, email string, limit int) ([]int64, error)

MessagesWithAddress uses FTS candidates and exact address checks to return at most limit nondeleted messages in view order.

func (*DB) NewestMessages

func (d *DB) NewestMessages(ctx context.Context, f NewestFilter) ([]NewestMessage, error)

NewestMessages returns, for each thread whose newest eligible message is dated within f's bounds, that message, newest first. A message's date is its Date header, else its arrival time, as its summary's.

func (*DB) NextDraftSave

func (d *DB) NextDraftSave(ctx context.Context, accountID int64) (at time.Time, ok bool, err error)

NextDraftSave returns the updated_at of the account's oldest draft whose server copy is missing or older than its content; ok is false when every copy is current. The saver waits until that time plus its quiet period.

func (*DB) NextOutboxDue

func (d *DB) NextOutboxDue(ctx context.Context, accountID int64) (at time.Time, ok bool, err error)

NextOutboxDue returns the earliest send_at of the account's queued messages; ok is false when none is queued.

func (*DB) OAuthClientID

func (d *DB) OAuthClientID(ctx context.Context, provider string) (string, error)

OAuthClientID returns the client ID stored for a provider; a missing one wraps ErrNotFound.

func (*DB) ObjectByHref

func (d *DB) ObjectByHref(ctx context.Context, collectionID int64, href string) (Object, error)

ObjectByHref returns the object at the exact href, or ErrNotFound.

func (*DB) ObjectETags

func (d *DB) ObjectETags(ctx context.Context, collectionID int64) (map[string]string, error)

ObjectETags returns every object's exact href and ETag in the collection.

func (*DB) ObjectRaws added in v0.8.0

func (d *DB) ObjectRaws(ctx context.Context, collectionID int64) (map[string][]byte, error)

ObjectRaws returns every object's source in the collection, by exact href, in 1 query.

func (*DB) ObjectRemotes

func (d *DB) ObjectRemotes(ctx context.Context, collectionID int64) (map[string][]byte, error)

ObjectRemotes returns, by href, the Graph JSON the collection's objects keep (ADR-0040); objects without one are left out.

func (*DB) Occurrences

func (d *DB) Occurrences(ctx context.Context, f OccurrenceFilter) ([]OccurrenceRow, error)

Occurrences returns stored occurrences.

func (*DB) OldestSeq

func (d *DB) OldestSeq(ctx context.Context) (int64, error)

OldestSeq is the lowest retained sequence number, or 0 when the log is empty.

func (*DB) OutboxInState

func (d *DB) OutboxInState(ctx context.Context, accountID int64, state string) ([]OutboxItem, error)

OutboxInState lists an account's messages (every account when accountID is 0) in one state, by ID.

func (*DB) PIMOpState

func (d *DB) PIMOpState(ctx context.Context, id int64) (state string, ok bool, err error)

PIMOpState is a change's state (queued, running or failed); ok is false once it is done and gone.

func (*DB) PendingHrefs

func (d *DB) PendingHrefs(ctx context.Context, collectionID int64) (map[string]bool, error)

PendingHrefs returns a set of hrefs with queued or running local operations.

func (*DB) People

func (d *DB) People(ctx context.Context, query string) ([]PersonRow, error)

People returns people ordered by sort key and ID, matching every query word against word prefixes in their name, organization and contacts' emails.

func (*DB) PeopleStale added in v0.8.0

func (d *DB) PeopleStale(ctx context.Context) (bool, error)

PeopleStale reports whether a transaction marked the people index stale after the last RelinkPeople.

func (*DB) Person

func (d *DB) Person(ctx context.Context, id int64) (PersonRow, error)

Person returns a person's list fields and ascending contact IDs, or ErrNotFound.

func (*DB) PersonByEmail

func (d *DB) PersonByEmail(ctx context.Context, email string) (PersonRow, error)

PersonByEmail returns the person of an eligible contact with the normalized email.

func (*DB) PersonEmails

func (d *DB) PersonEmails(ctx context.Context, personID int64) ([]string, error)

PersonEmails returns the lowercased addresses of a person's contacts, ascending, or ErrNotFound for no such person.

func (*DB) PersonOfContact

func (d *DB) PersonOfContact(ctx context.Context, objectID int64) (PersonRow, error)

PersonOfContact returns the person a contact belongs to, or ErrNotFound.

func (*DB) PersonPhoto

func (d *DB) PersonPhoto(ctx context.Context, id int64) ([]byte, string, error)

PersonPhoto returns the first photo in ascending contact order, or ErrNotFound.

func (*DB) PrefetchCandidates

func (d *DB) PrefetchCandidates(ctx context.Context, accountID int64, since time.Time, limit int) ([]int64, error)

PrefetchCandidates are the newest messages of an account, at most limit, that arrived at or after since, are in its INBOX or from a VIP, can be fetched (a mailbox holds them by UID), and have neither their whole body nor a display copy stored (ADR-0037).

func (*DB) PruneChanges

func (d *DB) PruneChanges(ctx context.Context, keep int) error

PruneChanges keeps the newest keep durable events.

func (*DB) QueuedOps

func (d *DB) QueuedOps(ctx context.Context, accountID int64, kind string) ([]Op, error)

QueuedOps returns an account's queued actions of one kind, due or not, oldest first.

func (*DB) RemindersChecked

func (d *DB) RemindersChecked(ctx context.Context) (at time.Time, ok bool, err error)

RemindersChecked returns when the reminder scheduler last checked; ok is false when it never has.

func (*DB) Rule

func (d *DB) Rule(ctx context.Context, id int64) (Rule, error)

Rule returns one rule, or ErrNotFound.

func (*DB) Rules

func (d *DB) Rules(ctx context.Context) ([]Rule, error)

Rules returns every rule in position order.

func (*DB) RulesWaiting

func (d *DB) RulesWaiting(ctx context.Context, accountID int64) ([]int64, error)

RulesWaiting returns an account's messages waiting for the rules, ascending.

func (*DB) SchemaVersion

func (d *DB) SchemaVersion(ctx context.Context) (int, error)

SchemaVersion is the highest applied migration.

func (*DB) ScopedPeople

func (d *DB) ScopedPeople(ctx context.Context, query string, accounts []int64) ([]PersonRow, error)

ScopedPeople returns, as People does, the people with a contact in the accounts' address books, each made of those contacts alone: the name, sort key, organization, photo and first email come from them, and the query matches their words only. It is what an agent whose scope names these accounts may see (ADR-0042).

func (*DB) ScopedPerson

func (d *DB) ScopedPerson(ctx context.Context, id int64, accounts []int64) (PersonRow, error)

ScopedPerson returns a person made of their contacts in the accounts' address books, as ScopedPeople does, or ErrNotFound when they have none.

func (*DB) SeenName

func (d *DB) SeenName(ctx context.Context, email string) (string, error)

SeenName returns the mail address index's name, or an empty string without a row.

func (*DB) SenderPhotos

func (d *DB) SenderPhotos(ctx context.Context, addresses []string) ([]SenderPhoto, error)

SenderPhotos returns those of addresses whose person has a photo, by address; addresses are lowercased.

func (*DB) Services

func (d *DB) Services(ctx context.Context, accountID int64) ([]Service, error)

Services returns an account's services rows, contacts, calendar, tasks; a service never turned on has none. accountID 0 returns every account's.

func (*DB) Settings

func (d *DB) Settings(ctx context.Context) (Settings, error)

Settings returns the preferences, defaults where nothing is stored.

func (*DB) SmartMailbox

func (d *DB) SmartMailbox(ctx context.Context, id int64) (SmartMailbox, error)

SmartMailbox returns one smart mailbox, or ErrNotFound.

func (*DB) SmartMailboxes

func (d *DB) SmartMailboxes(ctx context.Context) ([]SmartMailbox, error)

SmartMailboxes returns every smart mailbox in position order.

func (*DB) Snippet added in v0.6.0

func (d *DB) Snippet(ctx context.Context, id int64) (Snippet, error)

Snippet returns one snippet, or ErrNotFound.

func (*DB) Snippets added in v0.6.0

func (d *DB) Snippets(ctx context.Context) ([]Snippet, error)

Snippets returns every snippet by name without case, then by id. The sort is in Go so it also applies to non-ASCII names.

func (*DB) SnoozesEnded

func (d *DB) SnoozesEnded(ctx context.Context, since, until time.Time) ([]AlarmKey, error)

SnoozesEnded returns the reminders whose snooze ended in (since, until].

func (*DB) StoreID added in v0.3.0

func (d *DB) StoreID(ctx context.Context) (string, error)

StoreID returns the id of this database: 32 hex characters, drawn at random the first time it is asked for and kept in the database after that (ADR-0046). The Flatpak's maild names its keyring items with it. No client sees it, so it emits no event.

func (*DB) SuggestAddresses

func (d *DB) SuggestAddresses(ctx context.Context, prefix string, limit int) ([]Address, error)

SuggestAddresses returns up to limit addresses matching a typed prefix, highest count first, then most recently seen, then by address. A row matches when, case-insensitively, the address starts with the prefix, the name starts with it, or any later word of the name starts with it; LIKE metacharacters in the prefix are literal. An empty prefix returns nil, and a limit at or below 0 means 10.

func (*DB) SuggestContacts

func (d *DB) SuggestContacts(ctx context.Context, prefix string, limit int) ([]Address, error)

SuggestContacts returns distinct eligible emails matching an email or name-word prefix, ranked by mail frequency, recency, display name and email.

func (*DB) Summaries

func (d *DB) Summaries(ctx context.Context, ids []int64) ([]Summary, error)

Summaries returns the summaries of ids in the order given, skipping IDs that do not exist. Each summary carries the message's mailbox IDs in ascending order. No IDs returns an empty slice without querying.

func (*DB) Task

func (d *DB) Task(ctx context.Context, objectID int64) (TaskRow, error)

Task returns one task.

func (*DB) Tasks

func (d *DB) Tasks(ctx context.Context, f TaskFilter) ([]TaskRow, error)

Tasks returns the tasks of shown task lists in order.

func (*DB) ThreadMessageIDs

func (d *DB) ThreadMessageIDs(ctx context.Context, threadID int64) ([]int64, error)

ThreadMessageIDs returns the IDs of a thread's messages that are not deleted, oldest first (internal date, then the Date header, then ID). The slice is empty, never nil, when the thread exists but holds no such message. A thread with no such ID is ErrNotFound.

func (*DB) ThreadUnread added in v0.10.0

func (d *DB) ThreadUnread(ctx context.Context, f ViewFilter, ids []int64) (map[int64]int64, error)

ThreadUnread counts unread messages in each row's conversation within f's scope, ignoring its unread condition. Missing message IDs are omitted.

func (*DB) Tx

func (d *DB) Tx(ctx context.Context, fn func(*Tx) error) error

Tx runs fn in a write transaction: committed if fn returns nil, rolled back otherwise. Writers are serialized.

func (*DB) UnsavedDrafts

func (d *DB) UnsavedDrafts(ctx context.Context, accountID int64) ([]Draft, error)

UnsavedDrafts lists, as ListDrafts does, the drafts no stored message of their account holds (none has their Message-ID) and the Outbox does not hold (no queued, sending or failed row): those a Drafts mailbox lists as not yet saved until their server copy arrives (docs/design/send.md).

func (*DB) Unsubscribed

func (d *DB) Unsubscribed(ctx context.Context, key string) (bool, error)

Unsubscribed reports whether the user unsubscribed under key.

func (*DB) VIPs

func (d *DB) VIPs(ctx context.Context) ([]VIP, error)

VIPs returns every VIP by name (case-insensitively), then address.

func (*DB) ViewIDs

func (d *DB) ViewIDs(ctx context.Context, f ViewFilter) ([]int64, error)

ViewIDs returns the IDs of the messages matching f in viewOrder. Deleted messages never match; every other condition is added only for the filter fields that are set. The mailbox filter uses EXISTS, not a JOIN, so a message in several mailboxes appears once. Match and Exclude are FTS5 expressions over messages_fts; dates bound the arrival (internal) date. Role, and any of Roles, keep only messages in a mailbox of that role, in any account. Keep's messages pass the Unread condition but every other. Threads keeps one row per thread: its newest message among those that match every other condition, a message with no thread being its own thread. The result keeps the view's order.

func (*DB) WritableAddressBooks

func (d *DB) WritableAddressBooks(ctx context.Context) ([]Collection, error)

WritableAddressBooks returns enabled, writable books on writable accounts with contacts enabled, in account, default-first, position and ID order.

type Draft

type Draft struct {
	ID          int64
	AccountID   int64
	Kind        string // new, reply, replyall, forward
	SourceID    int64  // the message replied to or forwarded; 0 for none
	Content     DraftContent
	Attachments []DraftAttachment // in the order they were added
	MessageID   string            // without angle brackets; the sent message keeps it
	InReplyTo   string
	References  []string
	ServerUID   uint32    // the copy in the Drafts mailbox; 0 before the first save
	SavedAt     time.Time // when that copy was written; zero before the first save
	UpdatedAt   time.Time
	CreatedAt   time.Time
}

Draft is a message being written (docs/design/send.md, Drafts).

type DraftAttachment

type DraftAttachment struct {
	ID          int64
	BlobID      string
	Filename    string
	ContentType string
	Size        int64
}

DraftAttachment is a file attached to a draft, kept in the blob store.

type DraftContent

type DraftContent struct {
	IdentityID int64     `json:"identityId"`
	To         []Address `json:"to"`
	Cc         []Address `json:"cc"`
	Bcc        []Address `json:"bcc"`
	Subject    string    `json:"subject"`
	HTML       string    `json:"html"`
}

DraftContent is what a compose window edits (api.DraftContent).

type EventRow

type EventRow struct {
	ID           int64 // set by reads and by IndexEvents
	ObjectID     int64
	UID          string
	RecurrenceID string
	Summary      string
	Location     string
	Description  string
	AllDay       bool
	// Start and End: instants, or UTC midnights for all-day events, which
	// are stored as YYYY-MM-DD.
	Start, End    time.Time
	TZID          string
	Recurrence    string
	Status        string // confirmed, tentative, cancelled
	Transparent   bool
	Organizer     string // lowercased email
	OrganizerName string
	PartStat      string // the user's answer, or ""
	Sequence      int
	Attendees     []AttendeeRow
	Alarms        []AlarmRow
	// Set by reads: the event's calendar and account, and whether either
	// is read-only.
	CalendarID int64
	AccountID  int64
	ReadOnly   bool
}

EventRow is an events row with its attendees and alarms: one VEVENT's index (internal/calendar builds it).

type EventsFilter

type EventsFilter struct {
	// Visible keeps only enabled calendars of accounts with the calendar
	// service on.
	Visible bool
	// CalendarIDs, when not empty, keeps only these calendars.
	CalendarIDs []int64
}

EventsFilter selects events to expand.

type ExportedAccount

type ExportedAccount struct {
	ID    int64
	Email string
	OAuth bool // the account signs in with a refresh token, not a password
}

ExportedAccount is an account a Snapshot holds.

type FlagChange

type FlagChange struct {
	Seen     *bool
	Flagged  *bool
	Answered *bool
	Color    *int
}

FlagChange sets or clears flags; nil fields are left alone. A Color above 0 also flags the message; clearing Flagged also clears the color.

type FlagUpdate

type FlagUpdate struct {
	UID    uint32
	ModSeq uint64
	Flags  Flags
	Labels []string // Gmail; nil when not fetched
}

FlagUpdate is a message's flags as the server reports them, with its Gmail labels when they were fetched.

type Flags

type Flags struct {
	Seen      bool
	Flagged   bool
	Answered  bool
	Forwarded bool // the $Forwarded keyword
	Draft     bool
	Deleted   bool // \Deleted: marked for expunge; hidden from views
	// Color is 0 when unflagged, else 1-7: Mail.app's flag color
	// ($MailFlagBit0-2 read as a 3-bit number) plus one, so red, which has
	// no bits set, is 1.
	Color int
	// Keywords are the other keywords, sorted, without duplicates.
	Keywords []string
}

Flags are a message's flags as stored (docs/design/storage.md).

func FlagsFromIMAP

func FlagsFromIMAP(flags []string) Flags

FlagsFromIMAP maps IMAP flags and keywords to Flags, comparing names without case. \Seen, \Flagged, \Answered, \Draft and \Deleted set their fields; every other name starting with \ (such as \Recent and \*) is ignored. $Forwarded sets Forwarded. $MailFlagBit0, $MailFlagBit1 and $MailFlagBit2 are read as a 3-bit number, and Color is that number plus one when Flagged, else 0: red is Color 1 with no bits, and a color without Flagged means nothing. Every other non-empty name is a keyword, keeping the first spelling of each and sorted by lowercase.

func (Flags) IMAPFlags

func (f Flags) IMAPFlags() []string

IMAPFlags maps Flags back to the IMAP flags and keywords that represent them, in this order: \Seen, \Answered, \Flagged, \Deleted and \Draft if set, then $Forwarded if set, then, when Flagged and Color > 1, $MailFlagBit0, $MailFlagBit1 and $MailFlagBit2 for the set bits of Color-1, then the keywords as they are. A Color without Flagged is dropped. The result is nil when nothing is set.

type GmailResult

type GmailResult struct {
	Added     []int64 // new messages
	Changed   []int64 // stored messages that moved here or changed labels
	Mailboxes []int64 // label mailboxes whose membership changed
}

GmailResult is what InsertGmail changed.

type Identity

type Identity struct {
	ID            int64
	AccountID     int64
	Name          string
	Email         string
	ReplyTo       string
	SignatureHTML string
	IsDefault     bool
}

Identity is an address an account sends as, with its signature.

type IdentityUpdate

type IdentityUpdate struct {
	Name          *string
	ReplyTo       *string
	SignatureHTML *string
}

IdentityUpdate changes the non-nil fields of an identity.

type InstanceRow

type InstanceRow struct {
	EventID      int64
	RecurrenceID string
	AllDay       bool
	Start, End   time.Time // as EventRow's
}

InstanceRow is an instances row: one occurrence of an event.

type LocalCopy

type LocalCopy struct {
	UID     uint32
	Message int64
	// Queued is true when a queued action covers the message, whose local
	// state then differs from the server's until the replay.
	Queued bool
	// Labels are the message's Gmail label mailboxes, ascending.
	Labels []int64
	// contains filtered or unexported fields
}

LocalCopy is what the store holds at one UID of a mailbox, for the safety check (docs/design/accounts.md, Safety check).

func (LocalCopy) FlagsDiffer

func (c LocalCopy) FlagsDiffer(flags Flags) bool

FlagsDiffer reports whether flags, as the server reports them, differ from the stored ones.

type Location

type Location struct {
	AccountID   int64
	MailboxID   int64
	MailboxPath string
	UID         uint32
}

Location is where to fetch a message from on the server.

type Mailbox

type Mailbox struct {
	ID        int64
	AccountID int64
	Path      string
	Name      string
	Delimiter string
	Role      api.MailboxRole
	Total     int64
	Unread    int64
	Label     bool // a Gmail label (ADR-0012)
}

Mailbox is a mailboxes row with its local counts.

type MailboxMember

type MailboxMember struct {
	Message int64
	UID     uint32
}

MailboxMember is a message in a mailbox and its UID there; 0 while a move into the mailbox is pending.

type Membership

type Membership struct {
	MessageID   int64
	AccountID   int64
	MailboxID   int64
	MailboxPath string
	Role        api.MailboxRole
	UID         uint32 // 0 while a local move is pending
}

Membership is a message's place in one mailbox.

type MessageBody added in v0.8.0

type MessageBody struct {
	Blob    string // the raw message in the blob store; "" until fetched
	Display string // its display copy (ADR-0037); "" until fetched
	Subject string
}

MessageBody is the little a reader needs of a message besides its body: the blobs of its stored bodies and its subject.

type MessageCopy

type MessageCopy struct {
	ID        int64
	AccountID int64
	Roles     []string
}

MessageCopy is a stored message with a given Message-ID, and the roles of the mailboxes holding it.

type MessageDetail

type MessageDetail struct {
	Summary
	To              []Address
	Cc              []Address
	ReplyTo         []Address
	MessageID       string
	InReplyTo       string
	References      []string
	ListID          string
	ListUnsubscribe string
	AuthResults     string // the first Authentication-Results header
	Parts           []Part
	BlobID          string // the raw message in the blob store; "" until fetched
	DisplayBlobID   string // its display copy in the blob store (ADR-0037); "" until fetched
}

MessageDetail is everything about a message except its body.

type MessageHeader

type MessageHeader struct {
	UID             uint32
	ModSeq          uint64
	Flags           Flags
	InternalDate    time.Time
	Size            int64
	MessageID       string // without angle brackets
	InReplyTo       string
	References      []string
	Subject         string
	From            Address
	To              []Address
	Cc              []Address
	Bcc             []Address
	ReplyTo         []Address
	Date            time.Time // zero when the Date header is missing or invalid
	ListID          string
	ListUnsubscribe string
	AuthResults     string
	HasAttachments  bool
	Preview         string
	Parts           []Part
	// Gmail (ADR-0012): X-GM-MSGID, X-GM-THRID and X-GM-LABELS; zero and nil
	// elsewhere.
	GmMsgID uint64
	GmThrID uint64
	Labels  []string
}

MessageHeader is what a header fetch learns about one message in one mailbox (docs/design/sync.md, the reconcile pass).

type MessageReminder

type MessageReminder struct {
	MessageID int64
	AccountID int64
	RemindAt  time.Time
}

MessageReminder is a message's pending reminder.

type NewestFilter

type NewestFilter struct {
	// Accounts, when not nil, keeps their threads only.
	Accounts []int64
	// After and Until bound the newest message's date: after the one, at
	// or before the other.
	After, Until time.Time
}

NewestFilter selects threads by their newest message for the waiting queries (thread.awaitingReply and thread.awaitingOthers; ADR-0042).

type NewestMessage

type NewestMessage struct {
	MessageID, AccountID, ThreadID int64
	Date                           time.Time
	From                           Address
	To, Cc                         []Address
	ListID, ListUnsubscribe        string
	Answered                       bool
	Muted                          bool // its thread is muted (ADR-0028)
	InInbox                        bool // it is in a mailbox with the inbox role
}

NewestMessage is a thread's newest message, with what the waiting rules read of it.

type Object

type Object struct {
	ID           int64
	CollectionID int64
	Href         string
	ETag         string
	Kind         ObjectKind
	UID          string
	Raw          []byte
	// Remote is Graph's JSON for an object maild derives Raw from
	// (ADR-0040); nil for DAV and Google Tasks objects. PutObject keeps
	// the stored one when Remote is nil, as local edits leave it.
	Remote     []byte
	ParseError string
	UpdatedAt  time.Time
}

Object is an objects row: a contact, calendar object or Google task as the server sent it (ADR-0018).

type ObjectKind

type ObjectKind string

ObjectKind is what an object's source holds.

const (
	ObjectVCard  ObjectKind = "vcard"
	ObjectVEvent ObjectKind = "vevent"
	ObjectVTodo  ObjectKind = "vtodo"
	ObjectGTask  ObjectKind = "gtask"
	ObjectOther  ObjectKind = "other"
)

The object kinds.

type OccurrenceFilter

type OccurrenceFilter struct {
	// From and To bound timed occurrences ([From, To) overlaps);
	// FromDate and ToDate (YYYY-MM-DD) bound all-day ones.
	From, To         time.Time
	FromDate, ToDate string
	// CalendarIDs, when not empty, keeps only these calendars.
	CalendarIDs []int64
	// WithEmail, when set, keeps only events whose organizer or an
	// attendee has this (lowercased) address.
	WithEmail string
	// Limit, when positive, returns at most this many.
	Limit int
}

OccurrenceFilter selects stored occurrences.

type OccurrenceRow

type OccurrenceRow struct {
	Instance InstanceRow
	Event    EventRow // without Attendees and Alarms
}

OccurrenceRow is a stored occurrence with its event.

type Op

type Op struct {
	ID        int64
	AccountID int64
	Kind      string // flags, move, expunge
	Payload   []byte
	Attempts  int
}

Op is a queued offline action (docs/design/sync.md, offline actions). Its payload is owned by the sync engine.

type OutboxItem

type OutboxItem struct {
	ID         int64
	AccountID  int64
	DraftID    int64  // the draft it came from; 0 once the draft is gone
	State      string // queued, sending, accepted, sent, failed
	SendAt     time.Time
	BlobID     string   // the built message
	MessageID  string   // without angle brackets
	From       string   // the envelope sender
	Recipients []string // the envelope recipients: To, Cc and Bcc
	Subject    string
	To         []Address
	Attempts   int
	LastError  string
	Scheduled  bool // Send Later: due at a chosen time, not in its undo window
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

OutboxItem is a message on its way out (docs/design/send.md, Outbox).

type PIMOp

type PIMOp struct {
	ID           int64
	AccountID    int64
	CollectionID int64
	ObjectID     *int64 // nil once a delete removed the object
	Kind         string // put, delete, tasks.insert, tasks.patch, tasks.delete
	Href         string
	IfMatch      string // the ETag the change was made on; "" creates
	Payload      string // the patch as JSON, to apply again after a 412
	State        string // queued, running, failed
	Attempts     int
	NextTryAt    time.Time
	LastError    string
}

PIMOp is a pim_ops row: a change made here to a contact, event or task, waiting to be written to the server (docs/design/pim.md, Writes).

type Part

type Part struct {
	Path        string // IMAP part specifier: "1", "1.2"
	ContentType string // lowercase type/subtype
	Charset     string
	Encoding    string // lowercase Content-Transfer-Encoding
	Disposition string // inline, attachment or ""
	Filename    string
	ContentID   string // without angle brackets
	Size        int64
}

Part is one MIME part from BODYSTRUCTURE.

type PersonRow

type PersonRow struct {
	ID           int64
	DisplayName  string
	SortKey      string
	Organization string
	Email        string // the first email of the person's first contact, or ""
	HasPhoto     bool
	ContactIDs   []int64 // the object IDs of the person's contacts, ascending
}

PersonRow is a person as the People list and contact cards show them.

type Predicate

type Predicate struct {
	SQL  string
	Args []any
}

Predicate is compiled conditions: an SQL expression over messages m and its arguments, in order.

func CompileConditions

func CompileConditions(c api.Conditions, now time.Time, loc *time.Location) (Predicate, error)

CompileConditions compiles c into one predicate. Relative dates (today, within) are days in loc as of now. An empty list matches every message.

type ReminderRow

type ReminderRow struct {
	AlarmKey
	FiredAt      time.Time
	SnoozedUntil *time.Time
	// DueAt is when it is shown: TriggerAt, or SnoozedUntil once a snooze
	// ended.
	DueAt    time.Time
	Event    EventRow // without attendees and alarms
	Instance InstanceRow
}

ReminderRow is a fired reminder with its occurrence.

type RemoteCollection

type RemoteCollection struct {
	Href        string
	Name        string
	Description string
	Color       string
	Components  []string
	ReadOnly    bool
}

RemoteCollection is a collection as the server lists it.

type Restore

type Restore struct {
	ID        string
	AccountID int64
	CreatedAt time.Time
	Objects   []RestoreObject
}

Restore is what one write replaced, for people.restore and calendar.restore.

type RestoreObject

type RestoreObject struct {
	CollectionID int64
	Href         string
	UID          string
	Raw          []byte // nil when the write created the object
}

RestoreObject is one object a contact or event write touched, as it was before (ADR-0032).

type Rule

type Rule struct {
	ID         int64
	Name       string
	Position   int // from 0; rules run in position order
	Enabled    bool
	Conditions api.Conditions
	Actions    []api.RuleAction
}

Rule acts on new inbox mail and on chosen messages (ADR-0024, docs/design/organize.md, Rules).

type RuleUpdate added in v0.6.0

type RuleUpdate struct {
	Name       *string
	Enabled    *bool
	Conditions *api.Conditions
	Actions    *[]api.RuleAction
}

RuleUpdate changes the non-nil fields of a rule; a nil field keeps what is stored. Actions is a pointer so that an empty list, which a rule may not have, is still told apart from actions that are not given.

type SearchDoc

type SearchDoc struct {
	Subject         string
	From            string // names and addresses, space-separated
	To              string // To and Cc names and addresses
	Body            string // plain text; the preview until the body is fetched
	AttachmentNames string // space-separated file names
}

SearchDoc is the text indexed for one message.

func SearchDocFor

func SearchDocFor(h MessageHeader) SearchDoc

SearchDocFor is the search entry for a newly stored message: its subject, sender, recipients, preview and attachment names.

type SenderPhoto

type SenderPhoto struct {
	Address  string // lowercased
	PersonID int64
}

SenderPhoto is an address whose person has a photo.

type ServerConfig

type ServerConfig struct {
	Host     string
	Port     int
	TLS      api.TLSMode
	Username string
}

ServerConfig is one server's connection settings.

type ServerMailbox

type ServerMailbox struct {
	Path       string // decoded from modified UTF-7
	Delimiter  string // "" for a flat namespace
	Role       api.MailboxRole
	Attrs      []string // raw LIST attributes, such as \HasNoChildren
	Selectable bool     // false for \Noselect and \NonExistent
	Subscribed bool
}

ServerMailbox is one mailbox as LIST reports it, with its role resolved.

type Service

type Service struct {
	AccountID  int64
	Service    api.ServiceKind
	Enabled    bool
	URL        string     // where discovery starts, or the Tasks API's base URL
	Home       string     // the DAV home set found from URL; "" until discovered
	LastSyncAt *time.Time // the end of the last complete pass
	LastError  string
}

Service is an account_services row: one of an account's services besides mail (ADR-0017).

type Settings

type Settings struct {
	UndoDelay     int    // seconds a sent message waits: 0, 10, 20 or 30
	NotifyScope   string // api.NotifyScope
	NotifySmartID int64  // the smart mailbox of scope smart; 0 otherwise
	FlagNames     []string
	Favorites     []int64 // mailboxes in the sidebar's Favorites, in order
	BlockAction   string  // api.BlockAction: what new mail from a blocked sender does
	PreviewLines  int     // lines of preview in the message list: 0 to MaxPreviewLines
	TextSize      string  // api.TextSize: how large the desktop app draws its text
}

Settings are maild's preferences (ADR-0026, docs/design/organize.md, Settings); a setting without a row has its default.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings are the settings of a new database.

type SmartMailbox

type SmartMailbox struct {
	ID           int64
	Name         string
	Position     int // from 0, in sidebar order
	Conditions   api.Conditions
	IncludeTrash bool
	IncludeSent  bool
}

SmartMailbox is saved conditions listed as a mailbox (ADR-0023, docs/design/organize.md, Smart mailboxes).

type SmartMailboxUpdate added in v0.6.0

type SmartMailboxUpdate struct {
	Name         *string
	Conditions   *api.Conditions
	IncludeTrash *bool
	IncludeSent  *bool
}

SmartMailboxUpdate changes the non-nil fields of a smart mailbox; a nil field keeps what is stored.

type Snapshot

type Snapshot struct {
	SchemaVersion int // the highest applied migration in the copy
	Accounts      []ExportedAccount
	// StoreID is the source's store id (see DB.StoreID), empty when the
	// source has none yet. Export never makes one.
	StoreID string
}

Snapshot says what Export copied.

func Export

func Export(ctx context.Context, src, dst string) (Snapshot, error)

Export copies the database at src into the new file dst with VACUUM INTO, for moving it to another machine (mailctl export). It does not migrate src, as Open does, and it changes nothing in it: the copy keeps src's schema, which a newer maild migrates when it opens it. maild should be stopped, so that the copy is a still one. dst must not exist.

type Snippet added in v0.6.0

type Snippet struct {
	ID        int64
	Name      string
	HTML      string
	UpdatedAt time.Time
}

Snippet is a named piece of HTML kept in the local maild store.

type SnippetUpdate added in v0.6.0

type SnippetUpdate struct {
	Name *string
	HTML *string
}

SnippetUpdate changes the non-nil fields of a snippet.

type Summary

type Summary struct {
	ID             int64
	AccountID      int64
	MailboxIDs     []int64
	ThreadID       int64 // 0 until threaded
	Subject        string
	From           Address
	Date           time.Time // the Date header, else the internal date
	Preview        string
	Flags          Flags
	HasAttachments bool
	Size           int64
	ThreadCount    int64     // messages in the thread; 1 for a message alone
	RemindAt       time.Time // a pending Remind Me reminder; zero for none
	Muted          bool      // the conversation is muted (ADR-0028)
}

Summary is a message list row (api.MessageSummary).

type SyncState

type SyncState struct {
	UIDValidity   uint32
	UIDNext       uint32
	HighestModSeq uint64 // 0 without CONDSTORE
	ServerCount   uint32 // MESSAGES when the pass ended
	LastSyncAt    time.Time
}

SyncState is a mailbox's position in the reconcile pass (docs/design/sync.md).

type TaskChange

type TaskChange struct {
	Title     *string `json:"title,omitzero"`
	Notes     *string `json:"notes,omitzero"`
	Due       *string `json:"due,omitzero"` // YYYY-MM-DD, or "" to clear
	Completed *bool   `json:"completed,omitzero"`
	Parent    int64   `json:"parent,omitzero"`
}

TaskChange is the payload of a tasks.insert or tasks.patch op: the fields to send to Google, and for an insert the parent's object.

type TaskFilter

type TaskFilter struct {
	// ListID, when set, keeps one list.
	ListID int64
	// Completed includes completed tasks.
	Completed bool
	// DueBefore, when set (YYYY-MM-DD), keeps tasks due before that day.
	DueBefore string
}

TaskFilter selects tasks.

type TaskRow

type TaskRow struct {
	// ObjectID is the task's object: the task's ID in the API.
	ObjectID  int64
	UID       string
	ParentUID string
	Title     string
	Notes     string
	Due       string // YYYY-MM-DD, or ""
	Completed bool
	// CompletedAt is set when known.
	CompletedAt *time.Time
	Position    string
	// GmThrID is the Gmail thread a task made from mail links to; 0 for none.
	GmThrID int64
	// Set by reads: the task's list and account, whether either is
	// read-only, and the parent's object (0 when it has none in the list).
	ListID    int64
	AccountID int64
	ReadOnly  bool
	ParentID  int64
}

TaskRow is a tasks row (docs/design/pim.md, Tasks).

type Tx

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

Tx is a write transaction. Emit records events delivered after commit.

func (*Tx) AccountReadOnly

func (t *Tx) AccountReadOnly(ctx context.Context, id int64) (bool, error)

AccountReadOnly reports whether an account is read-only; a missing account is ErrNotFound.

func (*Tx) AccountSyncDays

func (t *Tx) AccountSyncDays(ctx context.Context, id int64) (int, error)

AccountSyncDays returns an account's sync window (ADR-0016); a missing account is ErrNotFound.

func (*Tx) AddDraftAttachment

func (t *Tx) AddDraftAttachment(ctx context.Context, draftID int64, a DraftAttachment) (DraftAttachment, error)

AddDraftAttachment attaches a stored blob to a draft and returns it with its new ID.

func (*Tx) AddIdentity

func (t *Tx) AddIdentity(ctx context.Context, accountID int64, name, email string) (Identity, error)

AddIdentity adds an address an account also sends and receives as (an alias), not its default, and returns it as stored. It wraps ErrNotFound for an unknown account and ErrConflict for an address the account already has, compared without case. account.changed follows.

func (*Tx) AddVIPs

func (t *Tx) AddVIPs(ctx context.Context, addresses []string) error

AddVIPs makes addresses VIPs (lowercased; ones already VIPs are left as they are), remembering the name seen with each, and emits api.VipChanged when one was added.

func (*Tx) AssignGmailThreads

func (t *Tx) AssignGmailThreads(ctx context.Context, accountID int64, ids []int64) ([]int64, error)

AssignGmailThreads puts messages in one thread per X-GM-THRID (JWZ threading for any without one) and refreshes the threads they joined.

func (*Tx) AssignThreads

func (t *Tx) AssignThreads(ctx context.Context, accountID int64, ids []int64) ([]int64, error)

AssignThreads puts each message in ids into a thread, in order, and returns the IDs of every thread it touched. It is incremental JWZ over thread_refs: every Message-ID a message carries (its own, In-Reply-To and References) maps to one thread. A message whose IDs reach no thread starts one; reaching one thread joins it; reaching several merges them into the oldest. A reply with no IDs at all (a subject with a Re: prefix) joins the newest thread with the same normalized subject seen within SubjectWindow. Thread aggregates are refreshed for the returned threads.

func (*Tx) Block

func (t *Tx) Block(ctx context.Context, addresses []string) error

Block blocks addresses (lowercased; ones already blocked stay as they are), remembering the name seen with each, and emits api.BlockChanged when one was added.

func (*Tx) CancelOutbox

func (t *Tx) CancelOutbox(ctx context.Context, id int64) (OutboxItem, error)

CancelOutbox returns a queued message as it was and deletes it. A missing message is an error wrapping ErrNotFound; a message in another state, one wrapping ErrConflict.

func (*Tx) ChangeFlags

func (t *Tx) ChangeFlags(ctx context.Context, ids []int64, c FlagChange) ([]int64, error)

ChangeFlags applies c to messages and returns the IDs whose flags changed.

func (*Tx) ClearMessageReminders

func (t *Tx) ClearMessageReminders(ctx context.Context, ids []int64) ([]int64, error)

ClearMessageReminders drops the messages' pending reminders and returns the IDs that had one.

func (*Tx) ClearRulesWaiting

func (t *Tx) ClearRulesWaiting(ctx context.Context, ids []int64) error

ClearRulesWaiting marks messages as no longer waiting for the rules.

func (*Tx) CreateDraft

func (t *Tx) CreateDraft(ctx context.Context, d Draft) (Draft, error)

CreateDraft stores a new draft with created_at and updated_at set to the transaction clock truncated to the millisecond; d.ID, ServerUID and SavedAt are ignored. It returns the stored draft as GetDraft reads it, with the new ID.

func (*Tx) CreateMailbox

func (t *Tx) CreateMailbox(ctx context.Context, accountID int64, path, delim string, label bool) (Mailbox, error)

CreateMailbox stores a mailbox made here, before the server has it: an ordinary selectable mailbox (a label on Gmail) with no sync state yet. It emits api.MailboxChanged.

func (*Tx) CreateRule

func (t *Tx) CreateRule(ctx context.Context, r Rule) (Rule, error)

CreateRule adds r at the end of the list and emits api.RuleChanged. The caller has checked it; r.ID and r.Position are ignored.

func (*Tx) CreateSmartMailbox

func (t *Tx) CreateSmartMailbox(ctx context.Context, s SmartMailbox) (SmartMailbox, error)

CreateSmartMailbox adds s at the end of the list and emits api.SmartChanged. The caller has checked its conditions; s.ID and s.Position are ignored.

func (*Tx) CreateSnippet added in v0.6.0

func (t *Tx) CreateSnippet(ctx context.Context, s Snippet) (Snippet, error)

CreateSnippet adds s and emits api.SnippetChanged; ErrConflict when its name is taken without case, ErrTooManySnippets at MaxSnippets.

func (*Tx) DeleteAccount

func (t *Tx) DeleteAccount(ctx context.Context, id int64) error

DeleteAccount deletes account id (its mailboxes and messages cascade) and emits api.AccountChanged{ID: id, Deleted: true}. A missing account returns ErrNotFound.

func (*Tx) DeleteDraft

func (t *Tx) DeleteDraft(ctx context.Context, id int64) (Draft, error)

DeleteDraft returns the draft as it was, attachments and server copy included, then deletes it; its attachments go with it through the foreign key cascade. A missing draft is an error wrapping ErrNotFound.

func (*Tx) DeleteIdentity

func (t *Tx) DeleteIdentity(ctx context.Context, id int64) error

DeleteIdentity removes an identity that is not its account's default; the drafts that used it move to the default. It wraps ErrNotFound, and ErrConflict for a default identity. account.changed follows.

func (*Tx) DeleteMailboxTree

func (t *Tx) DeleteMailboxTree(ctx context.Context, id int64) ([]string, error)

DeleteMailboxTree deletes a mailbox and those inside it, with the messages left in no mailbox and the account's role choices for them. It returns their paths, deepest first, and emits as ReplaceMailboxes does.

func (*Tx) DeleteObjects

func (t *Tx) DeleteObjects(ctx context.Context, collectionID int64, hrefs []string) (int, error)

DeleteObjects removes the named objects and returns how many existed.

func (*Tx) DeleteOp

func (t *Tx) DeleteOp(ctx context.Context, id int64) error

DeleteOp removes a replayed action; its messages take the server's flags again.

func (*Tx) DeleteOutbox

func (t *Tx) DeleteOutbox(ctx context.Context, id int64) error

DeleteOutbox removes an outbox row whatever its state (a failed send that a new send of its draft replaces). A missing row wraps ErrNotFound.

func (*Tx) DeleteRule

func (t *Tx) DeleteRule(ctx context.Context, id int64) error

DeleteRule removes a rule, closes the gap in the positions and emits api.RuleChanged.

func (*Tx) DeleteSmartMailbox

func (t *Tx) DeleteSmartMailbox(ctx context.Context, id int64) error

DeleteSmartMailbox removes a smart mailbox, closes the gap in the positions, makes a notification scope that named it Inbox only, and emits api.SmartChanged (and api.SettingsChanged when the scope moved).

func (*Tx) DeleteSnippet added in v0.6.0

func (t *Tx) DeleteSnippet(ctx context.Context, id int64) error

DeleteSnippet removes a snippet and emits api.SnippetChanged.

func (*Tx) DismissReminders

func (t *Tx) DismissReminders(ctx context.Context, keys []AlarmKey, at time.Time) (int, error)

DismissReminders stops showing reminders.

func (*Tx) DonePIMOp

func (t *Tx) DonePIMOp(ctx context.Context, id int64) error

DonePIMOp removes a change the server took.

func (*Tx) DropDeletesAfter

func (t *Tx) DropDeletesAfter(ctx context.Context, putID int64) ([]int64, error)

DropDeletesAfter removes the deletes waiting for a put (a move's, ADR-0030) when the server refused it, and returns their collections.

func (*Tx) DropGmailLabels

func (t *Tx) DropGmailLabels(ctx context.Context, msgID int64) ([]int64, error)

DropGmailLabels removes every label membership of a message, as moving it to Spam or Trash does, and returns the label mailboxes that changed.

func (*Tx) DropPIMOps

func (t *Tx) DropPIMOps(ctx context.Context, objectID int64) (int, error)

DropPIMOps removes an object's waiting changes, for an object deleted before the server ever had it, and returns how many there were.

func (*Tx) DropRestoresBefore

func (t *Tx) DropRestoresBefore(ctx context.Context, before time.Time) (int, error)

DropRestoresBefore removes the restores made before a time and returns how many there were.

func (*Tx) EditGmailLabels

func (t *Tx) EditGmailLabels(ctx context.Context, msgID int64, add, remove []int64) ([]int64, error)

EditGmailLabels adds and removes label memberships of a message and returns the label mailboxes that changed.

func (*Tx) Emit

func (t *Tx) Emit(ctx context.Context, ev api.Event) error

Emit records ev. A durable event is appended to the changes log in this transaction and gets its sequence number; every event is delivered to OnCommit only if the transaction commits.

func (*Tx) FailOp

func (t *Tx) FailOp(ctx context.Context, id int64, reason string) error

FailOp marks an action the server refused; it is not retried, and its messages take the server's flags again.

func (*Tx) FailOutbox

func (t *Tx) FailOutbox(ctx context.Context, id int64, reason string) error

FailOutbox marks a message the server refused, incrementing attempts and recording reason, only if it is sending. A missing message is an error wrapping ErrNotFound; a message in another state, one wrapping ErrConflict.

func (*Tx) FireMessageReminders

func (t *Tx) FireMessageReminders(ctx context.Context, ids []int64, now time.Time) error

FireMessageReminders drops the messages' reminders and lists them at now, at the top of their views.

func (*Tx) FireReminders

func (t *Tx) FireReminders(ctx context.Context, keys []AlarmKey, firedAt time.Time) error

FireReminders records alarms as fired.

func (*Tx) ForgetFlagState

func (t *Tx) ForgetFlagState(ctx context.Context, mailboxID int64) error

ForgetFlagState makes the next reconcile pass of a mailbox fetch every flag, so local state the server refused is replaced by the server's.

func (*Tx) GetAccount added in v0.6.0

func (t *Tx) GetAccount(ctx context.Context, id int64) (Account, error)

GetAccount is DB.GetAccount inside the transaction: a write that reads an account's optional fields reads them here, in the transaction that acts on them, so a concurrent update cannot slip in between.

func (*Tx) GetDraft

func (t *Tx) GetDraft(ctx context.Context, id int64) (Draft, error)

GetDraft is DB.GetDraft inside the transaction.

func (*Tx) GetMailbox

func (t *Tx) GetMailbox(ctx context.Context, id int64) (Mailbox, error)

GetMailbox is DB.GetMailbox inside the transaction.

func (*Tx) GetObject

func (t *Tx) GetObject(ctx context.Context, id int64) (Object, error)

GetObject returns one object as the transaction sees it, or ErrNotFound.

func (*Tx) GetOutbox

func (t *Tx) GetOutbox(ctx context.Context, id int64) (OutboxItem, error)

GetOutbox is DB.GetOutbox inside the transaction.

func (*Tx) GmailAccount

func (t *Tx) GmailAccount(ctx context.Context, accountID int64) (bool, error)

GmailAccount reports whether an account syncs the Gmail way: its labels are marked after its first Gmail pass, and INBOX is always one.

func (*Tx) GmailLabelNames

func (t *Tx) GmailLabelNames(ctx context.Context, accountID int64) (map[int64]string, error)

GmailLabelNames maps an account's label mailboxes to the X-GM-LABELS name that sets them: \Inbox, \Sent, \Draft, \Starred, \Important, or the label's path.

func (*Tx) GmailLabels

func (t *Tx) GmailLabels(ctx context.Context, accountID int64) (map[string]int64, error)

GmailLabels maps X-GM-LABELS names to an account's label mailboxes: \Inbox, \Sent, \Draft, \Starred and \Important by role or attribute, and every label by its path.

func (*Tx) HoldsEventUID added in v0.8.0

func (t *Tx) HoldsEventUID(ctx context.Context, uid string) (bool, error)

HoldsEventUID reports whether a calendar of any account holds an event with uid. It reads inside the transaction, so a write that depends on the answer cannot race another that stores the same UID.

func (*Tx) IndexContact

func (t *Tx) IndexContact(ctx context.Context, objectID int64, c ContactIndex) error

IndexContact replaces contact fields and normalized emails, each once, retaining person_id.

func (*Tx) IndexEvents

func (t *Tx) IndexEvents(ctx context.Context, objectID int64, events []EventRow) ([]int64, error)

IndexEvents stores an object's events, which have distinct recurrence IDs. An event whose recurrence ID the object already had keeps its ID, since clients hold event IDs; the object's other events are deleted, and its instances are dropped for ReplaceInstances to store again.

func (*Tx) IndexMessage

func (t *Tx) IndexMessage(ctx context.Context, id int64, doc SearchDoc) error

IndexMessage writes the search entry of message id, replacing any previous one. The messages_fts table is contentless, so a re-index is a delete of the old row followed by an insert.

func (*Tx) IndexTask

func (t *Tx) IndexTask(ctx context.Context, objectID int64, r TaskRow) error

IndexTask stores or replaces an object's task.

func (*Tx) InsertAccount

func (t *Tx) InsertAccount(ctx context.Context, a Account) (Account, error)

InsertAccount inserts a, ignoring a.ID and a.CreatedAt: the row gets a new ID and CreatedAt = tx.Now() truncated to the millisecond, and a default identity with the account's display name and email. It emits api.AccountChanged{ID: id} and returns the stored account. A duplicate email (case-insensitive) returns ErrConflict.

func (*Tx) InsertGmail

func (t *Tx) InsertGmail(ctx context.Context, accountID, mailboxID int64, allMail bool, labels map[string]int64, hs []MessageHeader) (GmailResult, error)

InsertGmail stores headers fetched from one synced folder of a Gmail account. A message already stored (by X-GM-MSGID) moves its UID membership here from the other synced folders and takes the reported flags; any other is inserted. Messages in All Mail get the labels of their header; messages in Spam and Trash have none. A header already stored at its UID is skipped, so a pass can be repeated.

func (*Tx) InsertHeaders

func (t *Tx) InsertHeaders(ctx context.Context, accountID, mailboxID int64, hs []MessageHeader) ([]int64, error)

InsertHeaders stores the messages in hs that mailboxID does not hold yet and returns their new IDs in the order of hs. A header whose UID is already in the mailbox is skipped, so a reconcile pass can be repeated after a crash. Each insert writes a messages row (body_state 'headers', thread_id NULL, subject_norm from mimex.NormalizeSubject, addresses and references as JSON arrays, date_hdr NULL for a zero Date), its message_mailbox row (uid, modseq, added_at) and its parts rows. It emits nothing: the sync engine threads, indexes and emits message.changed for the batch in the same transaction. Task T-0013 implements it.

func (*Tx) ListMailboxes

func (t *Tx) ListMailboxes(ctx context.Context, accountID int64) ([]Mailbox, error)

ListMailboxes is DB.ListMailboxes inside the transaction.

func (*Tx) MailboxByRole

func (t *Tx) MailboxByRole(ctx context.Context, accountID int64, role api.MailboxRole) (Mailbox, error)

MailboxByRole is DB.MailboxByRole inside the transaction.

func (*Tx) MailboxMembers

func (t *Tx) MailboxMembers(ctx context.Context, mailboxID int64) ([]MailboxMember, error)

MailboxMembers returns the messages in a mailbox that are not marked deleted, by message ID.

func (*Tx) MailboxUIDValidity added in v0.6.0

func (t *Tx) MailboxUIDValidity(ctx context.Context, mailboxID int64) (uint32, error)

MailboxUIDValidity returns the UIDVALIDITY maild stored for a mailbox, 0 while it has none (the mailbox was never selected); a missing mailbox is ErrNotFound.

func (*Tx) MarkDeleted

func (t *Tx) MarkDeleted(ctx context.Context, ids []int64) error

MarkDeleted hides messages locally until an expunge is confirmed.

func (*Tx) MarkGmailLabels

func (t *Tx) MarkGmailLabels(ctx context.Context, accountID int64) error

MarkGmailLabels marks every mailbox of a Gmail account as a label except All Mail, Spam and Trash, which are synced.

func (*Tx) MarkPeopleStale added in v0.8.0

func (t *Tx) MarkPeopleStale(ctx context.Context) error

MarkPeopleStale records that the transaction changed contacts and the people index waits for RelinkPeople. A sync pass marks each batch it commits and relinks once at its end; the mark is durable, so a pass that fails part-way leaves it for the next pass. RelinkPeople clears it.

func (*Tx) MarkRulesWaiting

func (t *Tx) MarkRulesWaiting(ctx context.Context, ids []int64) error

MarkRulesWaiting marks those of ids that are in an inbox (\Inbox on Gmail) as waiting for the rules (ADR-0024), in the transaction that stored them.

func (*Tx) Memberships

func (t *Tx) Memberships(ctx context.Context, ids []int64) ([]Membership, error)

Memberships returns the mailboxes holding each message, in message order.

func (*Tx) MessagesAtUIDs added in v0.8.0

func (t *Tx) MessagesAtUIDs(ctx context.Context, mailboxID int64, uids []uint32) (map[uint32]int64, error)

MessagesAtUIDs returns the message at each of uids in a mailbox, keyed by UID; a UID the mailbox does not hold has no entry. It takes 1 query for each 500 UIDs, so a caller with a batch of headers does not ask once for each header.

func (*Tx) MoveMembership

func (t *Tx) MoveMembership(ctx context.Context, messageID, from, to int64) error

MoveMembership moves a message from one mailbox to another locally, leaving its UID unknown until the server reports it. The row's added_at restarts: the message is new in the mailbox it comes to (ADR-0051).

func (*Tx) MoveOutbox

func (t *Tx) MoveOutbox(ctx context.Context, id int64, from, to string) error

MoveOutbox changes a message's state from one to another only if it is in the expected one, setting updated_at to the transaction clock. A missing message is an error wrapping ErrNotFound; a message in another state, one wrapping ErrConflict.

func (*Tx) MoveRule

func (t *Tx) MoveRule(ctx context.Context, id int64, position int) error

MoveRule puts a rule at position (clamped to the list), moving the others along, and emits api.RuleChanged.

func (*Tx) MoveSmartMailbox

func (t *Tx) MoveSmartMailbox(ctx context.Context, id int64, position int) error

MoveSmartMailbox puts a smart mailbox at position (clamped to the list), moving the others along, and emits api.SmartChanged.

func (*Tx) MuteThreads

func (t *Tx) MuteThreads(ctx context.Context, messageIDs []int64, muted bool) error

MuteThreads mutes or unmutes the conversations of messageIDs (ADR-0028) and emits api.MessageChanged, per account, for every message of them. Messages not yet in a conversation are left as they are.

func (*Tx) Now

func (t *Tx) Now() time.Time

Now is the database clock, for rows written in this transaction.

func (*Tx) OldMailboxMembers added in v0.6.0

func (t *Tx) OldMailboxMembers(ctx context.Context, mailboxID int64, before time.Time, limit int) ([]MailboxMember, error)

OldMailboxMembers returns at most limit of the messages in a mailbox that maild first saw there before the given time, oldest first: the erase pass takes these (ADR-0051). A message without a UID (a pending move) and one with no added_at are left out: neither can be erased by UID.

func (*Tx) OutboxOfDraft

func (t *Tx) OutboxOfDraft(ctx context.Context, draftID int64) ([]OutboxItem, error)

OutboxOfDraft lists the outbox rows made from a draft, by ID.

func (*Tx) PruneGmail

func (t *Tx) PruneGmail(ctx context.Context, accountID int64) ([]int64, error)

PruneGmail deletes the account's messages that belong to no mailbox (and their search entries) and returns their IDs.

func (*Tx) PutObject

func (t *Tx) PutObject(ctx context.Context, o Object) (int64, error)

PutObject stores source and metadata, preserving the ID at an existing href.

func (*Tx) QueueOp

func (t *Tx) QueueOp(ctx context.Context, accountID int64, kind string, payload any, messages []int64) (int64, error)

QueueOp records an action to replay against the server. messages are the messages it covers: until the action is deleted or fails, UpdateFlags leaves their flags alone.

func (*Tx) QueueOutbox

func (t *Tx) QueueOutbox(ctx context.Context, o OutboxItem) (OutboxItem, error)

QueueOutbox inserts a queued message with state queued, attempts 0 and an empty last_error; created_at and updated_at are the transaction clock. o.ID, State, Attempts, LastError and the times are ignored; Scheduled marks a Send Later row. It returns the row as GetOutbox reads it, with the new ID.

func (*Tx) QueuePIMOp

func (t *Tx) QueuePIMOp(ctx context.Context, op PIMOp) (int64, error)

QueuePIMOp queues a change, due at op.NextTryAt or now when that is zero, and returns its ID.

func (*Tx) QueuedPIMOp

func (t *Tx) QueuedPIMOp(ctx context.Context, objectID int64, kind string) (bool, error)

QueuedPIMOp reports whether an object has a change of a kind waiting (queued, not running): a later put need not be queued, since the waiting one writes the object's source as it is then.

func (*Tx) QueuedPut

func (t *Tx) QueuedPut(ctx context.Context, objectID int64) (PIMOp, bool, error)

QueuedPut returns the put waiting for an object (queued, not running), whose payload a later edit extends.

func (*Tx) RebasePIMOps

func (t *Tx) RebasePIMOps(ctx context.Context, collectionID int64, href, ifMatch, newHref, newETag string) (int64, error)

RebasePIMOps moves the waiting changes made on one version of an object (its href and the ETag they were made on) to the version a write left, the change written among them, and returns how many it moved.

func (*Tx) RecordAddresses

func (t *Tx) RecordAddresses(ctx context.Context, as []Address, seen time.Time) error

RecordAddresses counts addresses seen in mail. Each address with a non-empty trimmed Addr is counted once per call, keyed by its trimmed, lowercased address: a new row gets the trimmed name, count 1 and last_seen seen; an existing row gets count + 1, the given name when it is not empty (otherwise it keeps its name), and the later last_seen.

func (*Tx) RecordRestore

func (t *Tx) RecordRestore(ctx context.Context, r Restore) error

RecordRestore keeps what a write replaced, dated now.

func (*Tx) RecordUnsubscribe

func (t *Tx) RecordUnsubscribe(ctx context.Context, key string) error

RecordUnsubscribe remembers an unsubscribe under key.

func (*Tx) RefreshThreads

func (t *Tx) RefreshThreads(ctx context.Context, threadIDs []int64) error

RefreshThreads recomputes the counts and last date of threads from their messages, and deletes threads left without messages (their thread_refs go with them, so a later message with those IDs starts afresh).

func (*Tx) RelinkPeople

func (t *Tx) RelinkPeople(ctx context.Context) error

RelinkPeople joins eligible contacts transitively by email, retaining unchanged rows. Ineligible contacts lose their person; no events are emitted.

func (*Tx) RemoveContact

func (t *Tx) RemoveContact(ctx context.Context, objectID int64) error

RemoveContact removes contact fields and emails; an absent contact is harmless.

func (*Tx) RemoveDraftAttachment

func (t *Tx) RemoveDraftAttachment(ctx context.Context, draftID, attachmentID int64) error

RemoveDraftAttachment deletes an attachment only if it belongs to the given draft; otherwise, or when it is missing, it returns an error wrapping ErrNotFound.

func (*Tx) RemoveFromIndex

func (t *Tx) RemoveFromIndex(ctx context.Context, ids []int64) error

RemoveFromIndex deletes the search entries of ids; ids without an entry are ignored.

func (*Tx) RemoveGmailUIDs

func (t *Tx) RemoveGmailUIDs(ctx context.Context, mailboxID int64, uids []uint32) (msgs, mailboxes []int64, err error)

RemoveGmailUIDs drops the memberships of uids in a synced folder, and the label memberships of their messages, but keeps the messages: one that moved to another synced folder is found again by its X-GM-MSGID in that folder's pass. PruneGmail deletes those left without a folder. It returns the messages and the label mailboxes affected.

func (*Tx) RemoveTask

func (t *Tx) RemoveTask(ctx context.Context, objectID int64) error

RemoveTask deletes an object's task, if it has one.

func (*Tx) RemoveUIDs

func (t *Tx) RemoveUIDs(ctx context.Context, mailboxID int64, uids []uint32) ([]int64, error)

RemoveUIDs removes the memberships of uids in mailboxID, deletes the messages left in no mailbox together with their parts and search entries, and returns the deleted message IDs in ascending order. UIDs not in the mailbox are skipped. It emits nothing. Task T-0013 implements it.

func (*Tx) RemoveVIPs

func (t *Tx) RemoveVIPs(ctx context.Context, addresses []string) error

RemoveVIPs stops addresses being VIPs and emits api.VipChanged when one was.

func (*Tx) RenameMailbox

func (t *Tx) RenameMailbox(ctx context.Context, id int64, newPath string) error

RenameMailbox gives a mailbox the path newPath; the mailboxes inside it and the account's role choices follow. It emits api.MailboxChanged for each.

func (*Tx) ReparentTasks

func (t *Tx) ReparentTasks(ctx context.Context, collectionID int64, oldUID, newUID string) error

ReparentTasks points a list's subtasks at their parent's new UID (a task created here that Google gave an ID).

func (*Tx) ReplaceCollections

func (t *Tx) ReplaceCollections(ctx context.Context, accountID int64, kind api.CollectionKind, list []RemoteCollection) ([]Collection, error)

ReplaceCollections reconciles server metadata and removals, preserving settings and sync state. It chooses a writable default and emits AccountChanged on change.

func (*Tx) ReplaceInstances

func (t *Tx) ReplaceInstances(ctx context.Context, objectID int64, rows []InstanceRow) error

ReplaceInstances replaces the stored occurrences of an object's events.

func (*Tx) ReplaceMailboxes

func (t *Tx) ReplaceMailboxes(ctx context.Context, accountID int64, list []ServerMailbox) ([]Mailbox, error)

ReplaceMailboxes makes accountID's mailboxes match list, a full LIST result, and returns the account's mailboxes afterwards in ListMailboxes order, read through t. A path not stored yet is inserted; a stored path has its delimiter, name, role, attributes, selectable and subscribed columns updated, the roles after the account's own choices (Use This Mailbox For); a stored path missing from list is deleted, together with the messages left in no mailbox (and their search entries). Name is the last component of Path after Delimiter (the whole path when Delimiter is empty). It emits api.MailboxChanged for each mailbox inserted, changed or deleted (Deleted: true), and api.MessageRemoved for messages deleted with a mailbox. Task T-0012 implements it.

func (*Tx) RequeueOutbox

func (t *Tx) RequeueOutbox(ctx context.Context, id int64, sendAt time.Time) error

RequeueOutbox queues a failed message again at sendAt, keeping its attempts and last error, only if it is failed. A missing message is an error wrapping ErrNotFound; a message in another state, one wrapping ErrConflict.

func (*Tx) RescheduleOutbox

func (t *Tx) RescheduleOutbox(ctx context.Context, id int64, sendAt time.Time, scheduled bool, blobID string) error

RescheduleOutbox gives a queued message a new time, Send Later or not, and the message rebuilt for it, only if it is queued. A missing message is an error wrapping ErrNotFound; a message in another state, one wrapping ErrConflict.

func (*Tx) RetryOutboxLater

func (t *Tx) RetryOutboxLater(ctx context.Context, id int64, sendAt time.Time, reason string) error

RetryOutboxLater puts a message that failed to send back in the queue at sendAt, incrementing attempts and recording reason, only if it is sending. A missing message is an error wrapping ErrNotFound; a message in another state, one wrapping ErrConflict.

func (*Tx) RetryPIMOp

func (t *Tx) RetryPIMOp(ctx context.Context, id int64, next time.Time, errText string) error

RetryPIMOp counts a failed attempt and waits until next; with next zero the change has failed for good and the server's version stands.

func (*Tx) ServiceSynced

func (t *Tx) ServiceSynced(ctx context.Context, accountID int64, service api.ServiceKind, at time.Time, errText string) error

ServiceSynced records the end of a pass of an account's service: the time of a complete pass, or the error that ended it. It emits api.AccountChanged only when the error changes.

func (*Tx) SetBody

func (t *Tx) SetBody(ctx context.Context, id int64, blobID string) error

SetBody records that a message's raw body is stored in the blob store under blobID, moving body_state to 'full'. A missing message is ErrNotFound.

func (*Tx) SetCollectionSync

func (t *Tx) SetCollectionSync(ctx context.Context, id int64, token, ctag string) error

SetCollectionSync records the completed pass's token, ctag and timestamp.

func (*Tx) SetDisplay

func (t *Tx) SetDisplay(ctx context.Context, id int64, blobID string) error

SetDisplay records that a message's display copy (ADR-0037) is stored in the blob store under blobID. A missing message is ErrNotFound.

func (*Tx) SetDraftServerCopy

func (t *Tx) SetDraftServerCopy(ctx context.Context, id int64, uid uint32, savedAt time.Time) error

SetDraftServerCopy records a draft's server copy UID and the time it was written. A missing draft is an error wrapping ErrNotFound.

func (*Tx) SetGmailLabels

func (t *Tx) SetGmailLabels(ctx context.Context, mailboxID int64, uid uint32, labels []string, labelMap map[string]int64) (msgID int64, mailboxes []int64, found bool, err error)

SetGmailLabels replaces the label memberships of the message at uid in a synced folder with labels (unknown names are skipped), returning the message and the label mailboxes that changed; found is false when the folder has no message at uid. Like UpdateFlags, it leaves a message a queued action covers as it is.

func (*Tx) SetGrantedScopes

func (t *Tx) SetGrantedScopes(ctx context.Context, id int64, scopes string) error

SetGrantedScopes records the scopes a new OAuth grant covers and announces the change.

func (*Tx) SetInstanceWindow

func (t *Tx) SetInstanceWindow(ctx context.Context, from, to time.Time) error

SetInstanceWindow records the dates the instances cover.

func (*Tx) SetMailboxRole

func (t *Tx) SetMailboxRole(ctx context.Context, id int64, role api.MailboxRole) error

SetMailboxRole makes a mailbox its account's mailbox of role, over the server's choice, now and at every later listing; the mailbox that had the role loses it. It emits api.MailboxChanged for both.

func (*Tx) SetMailboxSyncState

func (t *Tx) SetMailboxSyncState(ctx context.Context, mailboxID int64, s SyncState) error

SetMailboxSyncState stores every field of s for the mailbox; a zero LastSyncAt is stored as NULL. It emits nothing. An unknown mailbox returns ErrNotFound. Task T-0012 implements it.

func (*Tx) SetMembership

func (t *Tx) SetMembership(ctx context.Context, messageID, mailboxID int64, uid uint32) error

SetMembership records a message's mailbox and UID once the server confirmed a move (uid 0 leaves it unknown), clearing pending. A row that comes to another mailbox restarts its added_at, as MoveMembership's does; one that stays keeps the time it had (ADR-0051).

func (*Tx) SetMessageReminders

func (t *Tx) SetMessageReminders(ctx context.Context, ids []int64, at time.Time) error

SetMessageReminders gives messages a reminder at at, replacing any they had. The caller checks that the messages exist.

func (*Tx) SetNeedsReauth

func (t *Tx) SetNeedsReauth(ctx context.Context, id int64, needs bool) error

SetNeedsReauth records whether the account's stored credential was refused, and announces the change.

func (*Tx) SetOAuthClientID

func (t *Tx) SetOAuthClientID(ctx context.Context, provider, clientID string) error

SetOAuthClientID stores a provider's client ID, replacing any previous one.

func (*Tx) SetObjectETag

func (t *Tx) SetObjectETag(ctx context.Context, id int64, etag string) error

SetObjectETag records the ETag the server gave an object Frostmail wrote.

func (*Tx) SetObjectHref

func (t *Tx) SetObjectHref(ctx context.Context, id int64, href string) error

SetObjectHref moves an object to the href the server gave it (a task created here gets its ID from Google).

func (*Tx) SetObjectRemote

func (t *Tx) SetObjectRemote(ctx context.Context, id int64, remote []byte) error

SetObjectRemote records the JSON of the server's version of an object derived from it (Graph's), beside a local source that stays.

func (*Tx) SetPIMOpPayload

func (t *Tx) SetPIMOpPayload(ctx context.Context, id int64, payload string) error

SetPIMOpPayload replaces a waiting change's payload.

func (*Tx) SetRemindersChecked

func (t *Tx) SetRemindersChecked(ctx context.Context, at time.Time) error

SetRemindersChecked records the reminder scheduler's check at at.

func (*Tx) SetSMTPMaxSize added in v0.10.0

func (t *Tx) SetSMTPMaxSize(ctx context.Context, accountID, size int64) error

SetSMTPMaxSize saves the server's SIZE without an API event. A missing account is harmless: it can be removed while a message is sent.

func (*Tx) SetService

func (t *Tx) SetService(ctx context.Context, accountID int64, service api.ServiceKind, enabled bool, url string) error

SetService stores whether an account's service is on and where it lives; a new URL forgets the home set and the last pass. It emits api.AccountChanged.

func (*Tx) SetServiceHome

func (t *Tx) SetServiceHome(ctx context.Context, accountID int64, service api.ServiceKind, home string) error

SetServiceHome records the home set discovery found for a service, or clears it ("") so the next pass discovers again.

func (*Tx) SetSettings

func (t *Tx) SetSettings(ctx context.Context, s Settings) error

SetSettings stores every setting of s and emits api.SettingsChanged. The caller has checked the values.

func (*Tx) Snippet added in v0.6.0

func (t *Tx) Snippet(ctx context.Context, id int64) (Snippet, error)

Snippet returns one snippet from a transaction.

func (*Tx) SnoozeReminders

func (t *Tx) SnoozeReminders(ctx context.Context, keys []AlarmKey, until time.Time) (int, error)

SnoozeReminders shows reminders again at until.

func (*Tx) TakeQueuedDelete

func (t *Tx) TakeQueuedDelete(ctx context.Context, collectionID int64, href string) (PIMOp, bool, error)

TakeQueuedDelete removes a delete waiting for an href (queued, not running) and returns it: a restore that comes before the delete was written keeps the server's object instead.

func (*Tx) TakeRestore

func (t *Tx) TakeRestore(ctx context.Context, id string) (Restore, error)

TakeRestore reads a restore and removes it, so it runs once: ErrNotFound when there is none (never made, used, or dropped after a day).

func (*Tx) ThreadsOf

func (t *Tx) ThreadsOf(ctx context.Context, messageIDs []int64) ([]int64, error)

ThreadsOf returns the distinct thread IDs of messages, for RefreshThreads after their flags change or before they are removed.

func (*Tx) ThreadsOfUIDs

func (t *Tx) ThreadsOfUIDs(ctx context.Context, mailboxID int64, uids []uint32) ([]int64, error)

ThreadsOfUIDs returns the distinct thread IDs of the messages at uids in mailboxID, for RefreshThreads after RemoveUIDs.

func (*Tx) TouchDraft

func (t *Tx) TouchDraft(ctx context.Context, id int64) error

TouchDraft sets a draft's updated_at to the transaction clock, so its server copy is saved again (its attachments changed). A missing draft wraps ErrNotFound.

func (*Tx) Unblock

func (t *Tx) Unblock(ctx context.Context, addresses []string) error

Unblock unblocks addresses and emits api.BlockChanged when one was blocked.

func (*Tx) UnseenInMailbox added in v0.8.0

func (t *Tx) UnseenInMailbox(ctx context.Context, mailboxID int64) ([]int64, error)

UnseenInMailbox returns the unread messages in a mailbox, by ID. It reads inside the transaction that marks them, so mail arriving meanwhile is either marked with them or left for the next call, never half of it.

func (*Tx) UpdateAccount

func (t *Tx) UpdateAccount(ctx context.Context, id int64, u AccountUpdate) (Account, error)

UpdateAccount applies u to account id, emits api.AccountChanged{ID: id} and returns the updated account. A missing account returns ErrNotFound.

func (*Tx) UpdateCollection

func (t *Tx) UpdateCollection(ctx context.Context, id int64, enabled *bool, makeDefault bool) (Collection, error)

UpdateCollection changes enabled and default settings and emits AccountChanged; showing or hiding a collection also emits its domain's change event, since what the domain's queries return changed.

func (*Tx) UpdateDraftContent

func (t *Tx) UpdateDraftContent(ctx context.Context, id int64, c DraftContent) (Draft, error)

UpdateDraftContent replaces a draft's content, sets updated_at to the transaction clock (see bumpUpdatedAt) and returns the draft as stored. A missing draft is an error wrapping ErrNotFound.

func (*Tx) UpdateFlags

func (t *Tx) UpdateFlags(ctx context.Context, mailboxID int64, ups []FlagUpdate) ([]int64, error)

UpdateFlags applies server-reported flags to the messages of mailboxID by UID and returns, in the order of ups, the IDs of messages whose stored flags changed. Every matched membership gets the update's modseq; UIDs not in the mailbox are skipped, and so are the flags of messages a queued action covers (QueueOp), whose local state stands until the replay. It emits nothing.

func (*Tx) UpdateIdentity

func (t *Tx) UpdateIdentity(ctx context.Context, id int64, u IdentityUpdate) (Identity, error)

UpdateIdentity changes an identity and returns it as stored; a missing one wraps ErrNotFound.

func (*Tx) UpdateRule

func (t *Tx) UpdateRule(ctx context.Context, id int64, u RuleUpdate) (Rule, error)

UpdateRule changes the given fields of a rule and emits api.RuleChanged, returning the row as stored. It reads the row inside its transaction, so a change it does not give is kept (ErrNotFound when there is no such rule). The caller has checked the conditions and actions it gives.

func (*Tx) UpdateSmartMailbox

func (t *Tx) UpdateSmartMailbox(ctx context.Context, id int64, u SmartMailboxUpdate) (SmartMailbox, error)

UpdateSmartMailbox changes the given fields of a smart mailbox and emits api.SmartChanged, returning the row as stored. It reads the row inside its transaction, so a change it does not give is kept (ErrNotFound when there is no such smart mailbox). The caller has checked the conditions it gives.

func (*Tx) UpdateSnippet added in v0.6.0

func (t *Tx) UpdateSnippet(ctx context.Context, id int64, u SnippetUpdate) (Snippet, error)

UpdateSnippet changes the given fields of a snippet and returns it as stored; an unknown id wraps ErrNotFound. It emits api.SnippetChanged.

func (*Tx) UpdateSystemFlags

func (t *Tx) UpdateSystemFlags(ctx context.Context, mailboxID int64, ups []FlagUpdate) ([]int64, error)

UpdateSystemFlags is UpdateFlags for a server that keeps no keywords (providers.Quirks.NoKeywords): a message keeps its stored keywords, and its stored flag color while the server has it flagged.

func (*Tx) UseServerDefault

func (t *Tx) UseServerDefault(ctx context.Context, accountID int64, kind api.CollectionKind, href string) (bool, error)

UseServerDefault makes the writable collection at href the default of its kind for the account, as the server names it, unless the user chose one (UpdateCollection). It reports whether the default changed, and emits AccountChanged when it did.

type VIP

type VIP struct {
	Address  string // lowercased
	Name     string // the person's in People, else the one seen in mail, else ""
	PersonID int64  // 0 when People has no person with the address
}

VIP is one VIP address (ADR-0026, docs/design/organize.md, VIPs).

type ViewFilter

type ViewFilter struct {
	AccountID int64
	// Accounts, when not nil, keeps only these accounts' messages, whatever
	// else the filter says: an agent's scope (docs/specs/lodge-app.md). An
	// empty, non-nil list keeps none.
	Accounts  []int64
	MailboxID int64
	Unread    *bool // true: unseen only; false: seen only
	Flagged   *bool
	Role      string // a mailbox role (api.MailboxRole), in any account
	Threads   bool   // one row per thread: its newest matching message
	// Keep lists messages that match even when Unread does not: the rows of
	// an open view, which stay when they are read (or marked unread).
	Keep []int64

	// A search (docs/specs/search.md), as internal/search parses it.
	Match         string    // FTS5 expression every message must match
	Exclude       string    // FTS5 expression no message may match
	HasAttachment *bool     // has:attachment
	After, Before time.Time // arrival in [After, Before)
	Roles         []string  // in: any of these mailbox roles

	// Conditions (ADR-0023), compiled each time the view is computed so
	// relative dates move along; checked with CheckConditions first.
	Conditions *api.Conditions
	// Filter is more conditions that must also hold (the filter bar's).
	Filter *api.Conditions
	// SmartMailboxID lists a smart mailbox, read each time so an edit
	// shows at the next recompute; an unknown one lists nothing.
	SmartMailboxID int64

	// Sort orders the rows by an api.ViewSort other than date; Ascending
	// puts the lowest first. Ties keep viewOrder.
	Sort      string
	Ascending bool
}

ViewFilter selects the messages of a view (api.ViewQuery). Zero fields do not filter.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL