1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "string-util.h"
33 #include <glib.h> /* g_free, GPtrArray, GHashTable */
34 #include <glib-object.h> /* g_type_init */
36 #include <gmime/gmime.h> /* g_mime_init */
40 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
47 #define NOTMUCH_DATABASE_VERSION 3
49 #define STRINGIFY(s) _SUB_STRINGIFY(s)
50 #define _SUB_STRINGIFY(s) #s
52 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
54 * We currently have three different types of documents (mail, ghost,
55 * and directory) and also some metadata.
59 * A mail document is associated with a particular email message. It
60 * is stored in one or more files on disk (though only one has its
61 * content indexed) and is uniquely identified by its "id" field
62 * (which is generally the message ID). It is indexed with the
63 * following prefixed terms which the database uses to construct
66 * Single terms of given prefix:
70 * id: Unique ID of mail. This is from the Message-ID header
71 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
72 * If it's present and too long, then we use
73 * "notmuch-sha1-<sha1_sum_of_message_id>".
74 * If this header is not present, we use
75 * "notmuch-sha1-<sha1_sum_of_entire_file>".
77 * thread: The ID of the thread to which the mail belongs
79 * replyto: The ID from the In-Reply-To header of the mail (if any).
81 * Multiple terms of given prefix:
83 * reference: All message IDs from In-Reply-To and References
84 * headers in the message.
86 * tag: Any tags associated with this message by the user.
88 * file-direntry: A colon-separated pair of values
89 * (INTEGER:STRING), where INTEGER is the
90 * document ID of a directory document, and
91 * STRING is the name of a file within that
92 * directory for this mail message.
94 * A mail document also has four values:
96 * TIMESTAMP: The time_t value corresponding to the message's
99 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
101 * FROM: The value of the "From" header
103 * SUBJECT: The value of the "Subject" header
105 * LAST_MOD: The revision number as of the last tag or
108 * In addition, terms from the content of the message are added with
109 * "from", "to", "attachment", and "subject" prefixes for use by the
110 * user in searching. Similarly, terms from the path of the mail
111 * message are added with "folder" and "path" prefixes. But the
112 * database doesn't really care itself about any of these.
114 * The data portion of a mail document is empty.
116 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
117 * -----------------------------------------------
118 * A ghost mail document is like a mail document, but where we don't
119 * have the message content. These are used to track thread reference
120 * information for messages we haven't received.
122 * A ghost mail document has type: ghost; id and thread fields that
123 * are identical to the mail document fields; and a MESSAGE_ID value.
127 * A directory document is used by a client of the notmuch library to
128 * maintain data necessary to allow for efficient polling of mail
131 * All directory documents contain one term:
133 * directory: The directory path (relative to the database path)
134 * Or the SHA1 sum of the directory path (if the
135 * path itself is too long to fit in a Xapian
138 * And all directory documents for directories other than top-level
139 * directories also contain the following term:
141 * directory-direntry: A colon-separated pair of values
142 * (INTEGER:STRING), where INTEGER is the
143 * document ID of the parent directory
144 * document, and STRING is the name of this
145 * directory within that parent.
147 * All directory documents have a single value:
149 * TIMESTAMP: The mtime of the directory (at last scan)
151 * The data portion of a directory document contains the path of the
152 * directory (relative to the database path).
156 * Xapian allows us to store arbitrary name-value pairs as
157 * "metadata". We currently use the following metadata names with the
160 * version The database schema version, (which is distinct
161 * from both the notmuch package version (see
162 * notmuch --version) and the libnotmuch library
163 * version. The version is stored as an base-10
164 * ASCII integer. The initial database version
165 * was 1, (though a schema existed before that
166 * were no "version" database value existed at
167 * all). Successive versions are allocated as
168 * changes are made to the database (such as by
169 * indexing new fields).
171 * features The set of features supported by this
172 * database. This consists of a set of
173 * '\n'-separated lines, where each is a feature
174 * name, a '\t', and compatibility flags. If the
175 * compatibility flags contain 'w', then the
176 * opener must support this feature to safely
177 * write this database. If the compatibility
178 * flags contain 'r', then the opener must
179 * support this feature to read this database.
180 * Introduced in database version 3.
182 * last_thread_id The last thread ID generated. This is stored
183 * as a 16-byte hexadecimal ASCII representation
184 * of a 64-bit unsigned integer. The first ID
185 * generated is 1 and the value will be
186 * incremented for each thread ID.
188 * C* metadata keys starting with C indicate
189 * configuration data. It can be managed with the
190 * n_database_*config* API. There is a convention
191 * of hierarchical keys separated by '.' (e.g.
192 * query.notmuch stores the value for the named
193 * query 'notmuch'), but it is not enforced by the
199 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
200 * Instead, the database has the following additional database
203 * thread_id_* A pre-allocated thread ID for a particular
204 * message. This is actually an arbitrarily large
205 * family of metadata name. Any particular name is
206 * formed by concatenating "thread_id_" with a message
207 * ID (or the SHA1 sum of a message ID if it is very
208 * long---see description of 'id' in the mail
209 * document). The value stored is a thread ID.
211 * These thread ID metadata values are stored
212 * whenever a message references a parent message
213 * that does not yet exist in the database. A
214 * thread ID will be allocated and stored, and if
215 * the message is later added, the stored thread
216 * ID will be used (and the metadata value will
219 * Even before a message is added, it's
220 * pre-allocated thread ID is useful so that all
221 * descendant messages that reference this common
222 * parent can be recognized as belonging to the
226 /* With these prefix values we follow the conventions published here:
228 * https://xapian.org/docs/omega/termprefixes.html
230 * as much as makes sense. Note that I took some liberty in matching
231 * the reserved prefix values to notmuch concepts, (for example, 'G'
232 * is documented as "newsGroup (or similar entity - e.g. a web forum
233 * name)", for which I think the thread is the closest analogue in
234 * notmuch. This in spite of the fact that we will eventually be
235 * storing mailing-list messages where 'G' for "mailing list name"
236 * might be even a closer analogue. I'm treating the single-character
237 * prefixes preferentially for core notmuch concepts (which will be
238 * nearly universal to all mail messages).
241 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
243 { "reference", "XREFERENCE" },
244 { "replyto", "XREPLYTO" },
245 { "directory", "XDIRECTORY" },
246 { "file-direntry", "XFDIRENTRY" },
247 { "directory-direntry", "XDDIRENTRY" },
250 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
257 * Without the ":", since this is a multi-letter prefix, Xapian
258 * will add a colon itself if the first letter of the path is
259 * upper-case ASCII. Including the ":" forces there to always be a
260 * colon, which keeps our own logic simpler.
262 { "folder", "XFOLDER:" },
265 static prefix_t PROBABILISTIC_PREFIX[]= {
268 { "attachment", "XATTACHMENT" },
269 { "mimetype", "XMIMETYPE"},
270 { "subject", "XSUBJECT"},
274 _find_prefix (const char *name)
278 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
279 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
280 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
283 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
284 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
285 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
288 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
289 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
290 return PROBABILISTIC_PREFIX[i].prefix;
293 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
298 static const struct {
299 /* NOTMUCH_FEATURE_* value. */
300 _notmuch_features value;
301 /* Feature name as it appears in the database. This name should
302 * be appropriate for displaying to the user if an older version
303 * of notmuch doesn't support this feature. */
305 /* Compatibility flags when this feature is declared. */
307 } feature_names[] = {
308 { NOTMUCH_FEATURE_FILE_TERMS,
309 "multiple paths per message", "rw" },
310 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
311 "relative directory paths", "rw" },
312 /* Header values are not required for reading a database because a
313 * reader can just refer to the message file. */
314 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
315 "from/subject/message-ID in database", "w" },
316 { NOTMUCH_FEATURE_BOOL_FOLDER,
317 "exact folder:/path: search", "rw" },
318 { NOTMUCH_FEATURE_GHOSTS,
319 "mail documents for missing messages", "w"},
320 /* Knowledge of the index mime-types are not required for reading
321 * a database because a reader will just be unable to query
323 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
324 "indexed MIME types", "w"},
325 { NOTMUCH_FEATURE_LAST_MOD,
326 "modification tracking", "w"},
330 notmuch_status_to_string (notmuch_status_t status)
333 case NOTMUCH_STATUS_SUCCESS:
334 return "No error occurred";
335 case NOTMUCH_STATUS_OUT_OF_MEMORY:
336 return "Out of memory";
337 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
338 return "Attempt to write to a read-only database";
339 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
340 return "A Xapian exception occurred";
341 case NOTMUCH_STATUS_FILE_ERROR:
342 return "Something went wrong trying to read or write a file";
343 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
344 return "File is not an email";
345 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
346 return "Message ID is identical to a message in database";
347 case NOTMUCH_STATUS_NULL_POINTER:
348 return "Erroneous NULL pointer";
349 case NOTMUCH_STATUS_TAG_TOO_LONG:
350 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
351 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
352 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
353 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
354 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
355 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
356 return "Unsupported operation";
357 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
358 return "Operation requires a database upgrade";
359 case NOTMUCH_STATUS_PATH_ERROR:
360 return "Path supplied is illegal for this function";
362 case NOTMUCH_STATUS_LAST_STATUS:
363 return "Unknown error status value";
368 _notmuch_database_log (notmuch_database_t *notmuch,
374 va_start (va_args, format);
376 if (notmuch->status_string)
377 talloc_free (notmuch->status_string);
379 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
385 find_doc_ids_for_term (notmuch_database_t *notmuch,
387 Xapian::PostingIterator *begin,
388 Xapian::PostingIterator *end)
390 *begin = notmuch->xapian_db->postlist_begin (term);
392 *end = notmuch->xapian_db->postlist_end (term);
396 find_doc_ids (notmuch_database_t *notmuch,
397 const char *prefix_name,
399 Xapian::PostingIterator *begin,
400 Xapian::PostingIterator *end)
404 term = talloc_asprintf (notmuch, "%s%s",
405 _find_prefix (prefix_name), value);
407 find_doc_ids_for_term (notmuch, term, begin, end);
412 notmuch_private_status_t
413 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
414 const char *prefix_name,
416 unsigned int *doc_id)
418 Xapian::PostingIterator i, end;
420 find_doc_ids (notmuch, prefix_name, value, &i, &end);
424 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
429 #if DEBUG_DATABASE_SANITY
433 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
437 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
440 static Xapian::Document
441 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
443 return notmuch->xapian_db->get_document (doc_id);
446 /* Generate a compressed version of 'message_id' of the form:
448 * notmuch-sha1-<sha1_sum_of_message_id>
451 _notmuch_message_id_compressed (void *ctx, const char *message_id)
453 char *sha1, *compressed;
455 sha1 = _notmuch_sha1_of_string (message_id);
457 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
464 notmuch_database_find_message (notmuch_database_t *notmuch,
465 const char *message_id,
466 notmuch_message_t **message_ret)
468 notmuch_private_status_t status;
471 if (message_ret == NULL)
472 return NOTMUCH_STATUS_NULL_POINTER;
474 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
475 message_id = _notmuch_message_id_compressed (notmuch, message_id);
478 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
479 message_id, &doc_id);
481 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
484 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
486 if (*message_ret == NULL)
487 return NOTMUCH_STATUS_OUT_OF_MEMORY;
490 return NOTMUCH_STATUS_SUCCESS;
491 } catch (const Xapian::Error &error) {
492 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
493 error.get_msg().c_str());
494 notmuch->exception_reported = TRUE;
496 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
500 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
501 * a (potentially nested) parenthesized sequence with '\' used to
502 * escape any character (including parentheses).
504 * If the sequence to be skipped continues to the end of the string,
505 * then 'str' will be left pointing at the final terminating '\0'
509 skip_space_and_comments (const char **str)
514 while (*s && (isspace (*s) || *s == '(')) {
515 while (*s && isspace (*s))
520 while (*s && nesting) {
523 } else if (*s == ')') {
525 } else if (*s == '\\') {
537 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
538 * comments, and the '<' and '>' delimiters.
540 * If not NULL, then *next will be made to point to the first character
541 * not parsed, (possibly pointing to the final '\0' terminator.
543 * Returns a newly talloc'ed string belonging to 'ctx'.
545 * Returns NULL if there is any error parsing the message-id. */
547 _parse_message_id (void *ctx, const char *message_id, const char **next)
552 if (message_id == NULL || *message_id == '\0')
557 skip_space_and_comments (&s);
559 /* Skip any unstructured text as well. */
560 while (*s && *s != '<')
571 skip_space_and_comments (&s);
574 while (*end && *end != '>')
583 if (end > s && *end == '>')
588 result = talloc_strndup (ctx, s, end - s + 1);
590 /* Finally, collapse any whitespace that is within the message-id
596 for (r = result, len = strlen (r); *r; r++, len--)
597 if (*r == ' ' || *r == '\t')
598 memmove (r, r+1, len);
604 /* Parse a References header value, putting a (talloc'ed under 'ctx')
605 * copy of each referenced message-id into 'hash'.
607 * We explicitly avoid including any reference identical to
608 * 'message_id' in the result (to avoid mass confusion when a single
609 * message references itself cyclically---and yes, mail messages are
610 * not infrequent in the wild that do this---don't ask me why).
612 * Return the last reference parsed, if it is not equal to message_id.
615 parse_references (void *ctx,
616 const char *message_id,
620 char *ref, *last_ref = NULL;
622 if (refs == NULL || *refs == '\0')
626 ref = _parse_message_id (ctx, refs, &refs);
628 if (ref && strcmp (ref, message_id)) {
629 g_hash_table_insert (hash, ref, NULL);
634 /* The return value of this function is used to add a parent
635 * reference to the database. We should avoid making a message
636 * its own parent, thus the above check.
642 notmuch_database_create (const char *path, notmuch_database_t **database)
644 char *status_string = NULL;
645 notmuch_status_t status;
647 status = notmuch_database_create_verbose (path, database,
651 fputs (status_string, stderr);
652 free (status_string);
659 notmuch_database_create_verbose (const char *path,
660 notmuch_database_t **database,
661 char **status_string)
663 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
664 notmuch_database_t *notmuch = NULL;
665 char *notmuch_path = NULL;
666 char *message = NULL;
671 message = strdup ("Error: Cannot create a database for a NULL path.\n");
672 status = NOTMUCH_STATUS_NULL_POINTER;
676 if (path[0] != '/') {
677 message = strdup ("Error: Database path must be absolute.\n");
678 status = NOTMUCH_STATUS_PATH_ERROR;
682 err = stat (path, &st);
684 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
685 path, strerror (errno)));
686 status = NOTMUCH_STATUS_FILE_ERROR;
690 if (! S_ISDIR (st.st_mode)) {
691 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
692 "Not a directory.\n",
694 status = NOTMUCH_STATUS_FILE_ERROR;
698 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
700 err = mkdir (notmuch_path, 0755);
703 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
704 notmuch_path, strerror (errno)));
705 status = NOTMUCH_STATUS_FILE_ERROR;
709 status = notmuch_database_open_verbose (path,
710 NOTMUCH_DATABASE_MODE_READ_WRITE,
715 /* Upgrade doesn't add these feature to existing databases, but
716 * new databases have them. */
717 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
718 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
720 status = notmuch_database_upgrade (notmuch, NULL, NULL);
722 notmuch_database_close(notmuch);
728 talloc_free (notmuch_path);
732 *status_string = message;
739 talloc_free (notmuch);
744 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
746 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
747 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
748 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
751 return NOTMUCH_STATUS_SUCCESS;
754 /* Allocate a revision number for the next change. */
756 _notmuch_database_new_revision (notmuch_database_t *notmuch)
758 unsigned long new_revision = notmuch->revision + 1;
760 /* If we're in an atomic section, hold off on updating the
761 * committed revision number until we commit the atomic section.
763 if (notmuch->atomic_nesting)
764 notmuch->atomic_dirty = TRUE;
766 notmuch->revision = new_revision;
771 /* Parse a database features string from the given database version.
772 * Returns the feature bit set.
774 * For version < 3, this ignores the features string and returns a
775 * hard-coded set of features.
777 * If there are unrecognized features that are required to open the
778 * database in mode (which should be 'r' or 'w'), return a
779 * comma-separated list of unrecognized but required features in
780 * *incompat_out suitable for presenting to the user. *incompat_out
781 * will be allocated from ctx.
783 static _notmuch_features
784 _parse_features (const void *ctx, const char *features, unsigned int version,
785 char mode, char **incompat_out)
787 _notmuch_features res = static_cast<_notmuch_features>(0);
788 unsigned int namelen, i;
792 /* Prior to database version 3, features were implied by the
795 return NOTMUCH_FEATURES_V0;
796 else if (version == 1)
797 return NOTMUCH_FEATURES_V1;
798 else if (version == 2)
799 return NOTMUCH_FEATURES_V2;
801 /* Parse the features string */
802 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
803 flags = strchr (features, '\t');
804 if (! flags || flags > features + llen)
806 namelen = flags - features;
808 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
809 if (strlen (feature_names[i].name) == namelen &&
810 strncmp (feature_names[i].name, features, namelen) == 0) {
811 res |= feature_names[i].value;
816 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
817 /* Unrecognized feature */
818 const char *have = strchr (flags, mode);
819 if (have && have < features + llen) {
820 /* This feature is required to access this database in
821 * 'mode', but we don't understand it. */
823 *incompat_out = talloc_strdup (ctx, "");
824 *incompat_out = talloc_asprintf_append_buffer (
825 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
835 _print_features (const void *ctx, unsigned int features)
838 char *res = talloc_strdup (ctx, "");
840 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
841 if (features & feature_names[i].value)
842 res = talloc_asprintf_append_buffer (
843 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
849 notmuch_database_open (const char *path,
850 notmuch_database_mode_t mode,
851 notmuch_database_t **database)
853 char *status_string = NULL;
854 notmuch_status_t status;
856 status = notmuch_database_open_verbose (path, mode, database,
860 fputs (status_string, stderr);
861 free (status_string);
868 notmuch_database_open_verbose (const char *path,
869 notmuch_database_mode_t mode,
870 notmuch_database_t **database,
871 char **status_string)
873 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
874 void *local = talloc_new (NULL);
875 notmuch_database_t *notmuch = NULL;
876 char *notmuch_path, *xapian_path, *incompat_features;
877 char *message = NULL;
880 unsigned int i, version;
881 static int initialized = 0;
884 message = strdup ("Error: Cannot open a database for a NULL path.\n");
885 status = NOTMUCH_STATUS_NULL_POINTER;
889 if (path[0] != '/') {
890 message = strdup ("Error: Database path must be absolute.\n");
891 status = NOTMUCH_STATUS_PATH_ERROR;
895 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
896 message = strdup ("Out of memory\n");
897 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
901 err = stat (notmuch_path, &st);
903 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
904 notmuch_path, strerror (errno)));
905 status = NOTMUCH_STATUS_FILE_ERROR;
909 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
910 message = strdup ("Out of memory\n");
911 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
915 /* Initialize the GLib type system and threads */
916 #if !GLIB_CHECK_VERSION(2, 35, 1)
920 /* Initialize gmime */
922 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
926 notmuch = talloc_zero (NULL, notmuch_database_t);
927 notmuch->exception_reported = FALSE;
928 notmuch->status_string = NULL;
929 notmuch->path = talloc_strdup (notmuch, path);
931 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
932 notmuch->path[strlen (notmuch->path) - 1] = '\0';
934 notmuch->mode = mode;
935 notmuch->atomic_nesting = 0;
937 string last_thread_id;
940 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
941 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
942 Xapian::DB_CREATE_OR_OPEN);
944 notmuch->xapian_db = new Xapian::Database (xapian_path);
947 /* Check version. As of database version 3, we represent
948 * changes in terms of features, so assume a version bump
949 * means a dramatically incompatible change. */
950 version = notmuch_database_get_version (notmuch);
951 if (version > NOTMUCH_DATABASE_VERSION) {
952 IGNORE_RESULT (asprintf (&message,
953 "Error: Notmuch database at %s\n"
954 " has a newer database format version (%u) than supported by this\n"
955 " version of notmuch (%u).\n",
956 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
957 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
958 notmuch_database_destroy (notmuch);
960 status = NOTMUCH_STATUS_FILE_ERROR;
964 /* Check features. */
965 incompat_features = NULL;
966 notmuch->features = _parse_features (
967 local, notmuch->xapian_db->get_metadata ("features").c_str (),
968 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
970 if (incompat_features) {
971 IGNORE_RESULT (asprintf (&message,
972 "Error: Notmuch database at %s\n"
973 " requires features (%s)\n"
974 " not supported by this version of notmuch.\n",
975 notmuch_path, incompat_features));
976 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
977 notmuch_database_destroy (notmuch);
979 status = NOTMUCH_STATUS_FILE_ERROR;
983 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
984 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
985 if (last_thread_id.empty ()) {
986 notmuch->last_thread_id = 0;
991 str = last_thread_id.c_str ();
992 notmuch->last_thread_id = strtoull (str, &end, 16);
994 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
997 /* Get current highest revision number. */
998 last_mod = notmuch->xapian_db->get_value_upper_bound (
999 NOTMUCH_VALUE_LAST_MOD);
1000 if (last_mod.empty ())
1001 notmuch->revision = 0;
1003 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1004 notmuch->uuid = talloc_strdup (
1005 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1007 notmuch->query_parser = new Xapian::QueryParser;
1008 notmuch->term_gen = new Xapian::TermGenerator;
1009 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1010 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1011 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1012 #if HAVE_XAPIAN_FIELD_PROCESSOR
1013 /* This currently relies on the query parser to pass anything
1014 * with a .. to the range processor */
1015 notmuch->date_field_processor = new DateFieldProcessor();
1016 notmuch->query_parser->add_boolean_prefix("date", notmuch->date_field_processor);
1017 notmuch->query_field_processor = new QueryFieldProcessor (*notmuch->query_parser, notmuch);
1018 notmuch->query_parser->add_boolean_prefix("query", notmuch->query_field_processor);
1020 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1022 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1023 notmuch->query_parser->set_database (*notmuch->xapian_db);
1024 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1025 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1026 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1027 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1028 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1030 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
1031 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
1032 notmuch->query_parser->add_boolean_prefix (prefix->name,
1036 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
1037 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
1038 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
1040 } catch (const Xapian::Error &error) {
1041 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1042 error.get_msg().c_str()));
1043 notmuch_database_destroy (notmuch);
1045 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1049 talloc_free (local);
1053 *status_string = message;
1059 *database = notmuch;
1061 talloc_free (notmuch);
1066 notmuch_database_close (notmuch_database_t *notmuch)
1068 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1070 /* Many Xapian objects (and thus notmuch objects) hold references to
1071 * the database, so merely deleting the database may not suffice to
1072 * close it. Thus, we explicitly close it here. */
1073 if (notmuch->xapian_db != NULL) {
1075 /* If there's an outstanding transaction, it's unclear if
1076 * closing the Xapian database commits everything up to
1077 * that transaction, or may discard committed (but
1078 * unflushed) transactions. To be certain, explicitly
1079 * cancel any outstanding transaction before closing. */
1080 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1081 notmuch->atomic_nesting)
1082 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1083 ->cancel_transaction ();
1085 /* Close the database. This implicitly flushes
1086 * outstanding changes. */
1087 notmuch->xapian_db->close();
1088 } catch (const Xapian::Error &error) {
1089 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1090 if (! notmuch->exception_reported) {
1091 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1092 error.get_msg().c_str());
1097 delete notmuch->term_gen;
1098 notmuch->term_gen = NULL;
1099 delete notmuch->query_parser;
1100 notmuch->query_parser = NULL;
1101 delete notmuch->xapian_db;
1102 notmuch->xapian_db = NULL;
1103 delete notmuch->value_range_processor;
1104 notmuch->value_range_processor = NULL;
1105 delete notmuch->date_range_processor;
1106 notmuch->date_range_processor = NULL;
1107 delete notmuch->last_mod_range_processor;
1108 notmuch->last_mod_range_processor = NULL;
1113 #if HAVE_XAPIAN_COMPACT
1115 unlink_cb (const char *path,
1116 unused (const struct stat *sb),
1118 unused (struct FTW *ftw))
1120 return remove (path);
1124 rmtree (const char *path)
1126 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1129 class NotmuchCompactor : public Xapian::Compactor
1131 notmuch_compact_status_cb_t status_cb;
1132 void *status_closure;
1135 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1136 status_cb (cb), status_closure (closure) { }
1139 set_status (const std::string &table, const std::string &status)
1143 if (status_cb == NULL)
1146 if (status.length () == 0)
1147 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1149 msg = talloc_asprintf (NULL, " %s", status.c_str());
1155 status_cb (msg, status_closure);
1160 /* Compacts the given database, optionally saving the original database
1161 * in backup_path. Additionally, a callback function can be provided to
1162 * give the user feedback on the progress of the (likely long-lived)
1163 * compaction process.
1165 * The backup path must point to a directory on the same volume as the
1166 * original database. Passing a NULL backup_path will result in the
1167 * uncompacted database being deleted after compaction has finished.
1168 * Note that the database write lock will be held during the
1169 * compaction process to protect data integrity.
1172 notmuch_database_compact (const char *path,
1173 const char *backup_path,
1174 notmuch_compact_status_cb_t status_cb,
1178 char *notmuch_path, *xapian_path, *compact_xapian_path;
1179 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1180 notmuch_database_t *notmuch = NULL;
1181 struct stat statbuf;
1182 notmuch_bool_t keep_backup;
1183 char *message = NULL;
1185 local = talloc_new (NULL);
1187 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1189 ret = notmuch_database_open_verbose (path,
1190 NOTMUCH_DATABASE_MODE_READ_WRITE,
1194 if (status_cb) status_cb (message, closure);
1198 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1199 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1203 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1204 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1208 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1209 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1213 if (backup_path == NULL) {
1214 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1215 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1218 keep_backup = FALSE;
1224 if (stat (backup_path, &statbuf) != -1) {
1225 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1226 ret = NOTMUCH_STATUS_FILE_ERROR;
1229 if (errno != ENOENT) {
1230 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1232 ret = NOTMUCH_STATUS_FILE_ERROR;
1236 /* Unconditionally attempt to remove old work-in-progress database (if
1237 * any). This is "protected" by database lock. If this fails due to write
1238 * errors (etc), the following code will fail and provide error message.
1240 (void) rmtree (compact_xapian_path);
1243 NotmuchCompactor compactor (status_cb, closure);
1245 compactor.set_renumber (false);
1246 compactor.add_source (xapian_path);
1247 compactor.set_destdir (compact_xapian_path);
1248 compactor.compact ();
1249 } catch (const Xapian::Error &error) {
1250 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1251 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1255 if (rename (xapian_path, backup_path)) {
1256 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1257 xapian_path, backup_path, strerror (errno));
1258 ret = NOTMUCH_STATUS_FILE_ERROR;
1262 if (rename (compact_xapian_path, xapian_path)) {
1263 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1264 compact_xapian_path, xapian_path, strerror (errno));
1265 ret = NOTMUCH_STATUS_FILE_ERROR;
1269 if (! keep_backup) {
1270 if (rmtree (backup_path)) {
1271 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1272 backup_path, strerror (errno));
1273 ret = NOTMUCH_STATUS_FILE_ERROR;
1280 notmuch_status_t ret2;
1282 const char *str = notmuch_database_status_string (notmuch);
1283 if (status_cb && str)
1284 status_cb (str, closure);
1286 ret2 = notmuch_database_destroy (notmuch);
1288 /* don't clobber previous error status */
1289 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1293 talloc_free (local);
1299 notmuch_database_compact (unused (const char *path),
1300 unused (const char *backup_path),
1301 unused (notmuch_compact_status_cb_t status_cb),
1302 unused (void *closure))
1304 _notmuch_database_log (notmuch, "notmuch was compiled against a xapian version lacking compaction support.\n");
1305 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1310 notmuch_database_destroy (notmuch_database_t *notmuch)
1312 notmuch_status_t status;
1314 status = notmuch_database_close (notmuch);
1315 talloc_free (notmuch);
1321 notmuch_database_get_path (notmuch_database_t *notmuch)
1323 return notmuch->path;
1327 notmuch_database_get_version (notmuch_database_t *notmuch)
1329 unsigned int version;
1330 string version_string;
1334 version_string = notmuch->xapian_db->get_metadata ("version");
1335 if (version_string.empty ())
1338 str = version_string.c_str ();
1339 if (str == NULL || *str == '\0')
1342 version = strtoul (str, &end, 10);
1344 INTERNAL_ERROR ("Malformed database version: %s", str);
1350 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1352 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1353 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1354 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1357 static volatile sig_atomic_t do_progress_notify = 0;
1360 handle_sigalrm (unused (int signal))
1362 do_progress_notify = 1;
1365 /* Upgrade the current database.
1367 * After opening a database in read-write mode, the client should
1368 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1369 * if so, upgrade with this function before making any modifications.
1371 * The optional progress_notify callback can be used by the caller to
1372 * provide progress indication to the user. If non-NULL it will be
1373 * called periodically with 'count' as the number of messages upgraded
1374 * so far and 'total' the overall number of messages that will be
1378 notmuch_database_upgrade (notmuch_database_t *notmuch,
1379 void (*progress_notify) (void *closure,
1383 void *local = talloc_new (NULL);
1384 Xapian::TermIterator t, t_end;
1385 Xapian::WritableDatabase *db;
1386 struct sigaction action;
1387 struct itimerval timerval;
1388 notmuch_bool_t timer_is_active = FALSE;
1389 enum _notmuch_features target_features, new_features;
1390 notmuch_status_t status;
1391 notmuch_private_status_t private_status;
1392 notmuch_query_t *query = NULL;
1393 unsigned int count = 0, total = 0;
1395 status = _notmuch_database_ensure_writable (notmuch);
1399 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1401 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1402 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1404 if (! notmuch_database_needs_upgrade (notmuch))
1405 return NOTMUCH_STATUS_SUCCESS;
1407 if (progress_notify) {
1408 /* Set up our handler for SIGALRM */
1409 memset (&action, 0, sizeof (struct sigaction));
1410 action.sa_handler = handle_sigalrm;
1411 sigemptyset (&action.sa_mask);
1412 action.sa_flags = SA_RESTART;
1413 sigaction (SIGALRM, &action, NULL);
1415 /* Then start a timer to send SIGALRM once per second. */
1416 timerval.it_interval.tv_sec = 1;
1417 timerval.it_interval.tv_usec = 0;
1418 timerval.it_value.tv_sec = 1;
1419 timerval.it_value.tv_usec = 0;
1420 setitimer (ITIMER_REAL, &timerval, NULL);
1422 timer_is_active = TRUE;
1425 /* Figure out how much total work we need to do. */
1427 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1428 NOTMUCH_FEATURE_LAST_MOD)) {
1429 query = notmuch_query_create (notmuch, "");
1432 status = notmuch_query_count_messages_st (query, &msg_count);
1437 notmuch_query_destroy (query);
1440 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1441 t_end = db->allterms_end ("XTIMESTAMP");
1442 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1445 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1446 /* The ghost message upgrade converts all thread_id_*
1447 * metadata values into ghost message documents. */
1448 t_end = db->metadata_keys_end ("thread_id_");
1449 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1453 /* Perform the upgrade in a transaction. */
1454 db->begin_transaction (true);
1456 /* Set the target features so we write out changes in the desired
1458 notmuch->features = target_features;
1460 /* Perform per-message upgrades. */
1462 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1463 NOTMUCH_FEATURE_LAST_MOD)) {
1464 notmuch_messages_t *messages;
1465 notmuch_message_t *message;
1468 query = notmuch_query_create (notmuch, "");
1470 status = notmuch_query_search_messages_st (query, &messages);
1474 notmuch_messages_valid (messages);
1475 notmuch_messages_move_to_next (messages))
1477 if (do_progress_notify) {
1478 progress_notify (closure, (double) count / total);
1479 do_progress_notify = 0;
1482 message = notmuch_messages_get (messages);
1484 /* Before version 1, each message document had its
1485 * filename in the data field. Copy that into the new
1486 * format by calling notmuch_message_add_filename.
1488 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1489 filename = _notmuch_message_talloc_copy_data (message);
1490 if (filename && *filename != '\0') {
1491 _notmuch_message_add_filename (message, filename);
1492 _notmuch_message_clear_data (message);
1494 talloc_free (filename);
1497 /* Prior to version 2, the "folder:" prefix was
1498 * probabilistic and stemmed. Change it to the current
1499 * boolean prefix. Add "path:" prefixes while at it.
1501 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1502 _notmuch_message_upgrade_folder (message);
1504 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1505 * track modification revisions. Give all messages the
1506 * next available revision; since we just started tracking
1507 * revisions for this database, that will be 1.
1509 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1510 _notmuch_message_upgrade_last_mod (message);
1512 _notmuch_message_sync (message);
1514 notmuch_message_destroy (message);
1519 notmuch_query_destroy (query);
1523 /* Perform per-directory upgrades. */
1525 /* Before version 1 we stored directory timestamps in
1526 * XTIMESTAMP documents instead of the current XDIRECTORY
1527 * documents. So copy those as well. */
1528 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1529 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1531 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1535 Xapian::PostingIterator p, p_end;
1536 std::string term = *t;
1538 p_end = notmuch->xapian_db->postlist_end (term);
1540 for (p = notmuch->xapian_db->postlist_begin (term);
1544 Xapian::Document document;
1546 notmuch_directory_t *directory;
1548 if (do_progress_notify) {
1549 progress_notify (closure, (double) count / total);
1550 do_progress_notify = 0;
1553 document = find_document_for_doc_id (notmuch, *p);
1554 mtime = Xapian::sortable_unserialise (
1555 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1557 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1558 NOTMUCH_FIND_CREATE, &status);
1559 notmuch_directory_set_mtime (directory, mtime);
1560 notmuch_directory_destroy (directory);
1562 db->delete_document (*p);
1569 /* Perform metadata upgrades. */
1571 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1572 * messages were stored as database metadata. Change these to
1575 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1576 notmuch_message_t *message;
1577 std::string message_id, thread_id;
1579 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1580 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1582 if (do_progress_notify) {
1583 progress_notify (closure, (double) count / total);
1584 do_progress_notify = 0;
1587 message_id = (*t).substr (
1588 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1589 thread_id = db->get_metadata (*t);
1591 /* Create ghost message */
1592 message = _notmuch_message_create_for_message_id (
1593 notmuch, message_id.c_str (), &private_status);
1594 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1595 /* Document already exists; ignore the stored thread ID */
1596 } else if (private_status ==
1597 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1598 private_status = _notmuch_message_initialize_ghost (
1599 message, thread_id.c_str ());
1600 if (! private_status)
1601 _notmuch_message_sync (message);
1604 if (private_status) {
1605 _notmuch_database_log (notmuch,
1606 "Upgrade failed while creating ghost messages.\n");
1607 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1611 /* Clear saved metadata thread ID */
1612 db->set_metadata (*t, "");
1618 status = NOTMUCH_STATUS_SUCCESS;
1619 db->set_metadata ("features", _print_features (local, notmuch->features));
1620 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1623 if (status == NOTMUCH_STATUS_SUCCESS)
1624 db->commit_transaction ();
1626 db->cancel_transaction ();
1628 if (timer_is_active) {
1629 /* Now stop the timer. */
1630 timerval.it_interval.tv_sec = 0;
1631 timerval.it_interval.tv_usec = 0;
1632 timerval.it_value.tv_sec = 0;
1633 timerval.it_value.tv_usec = 0;
1634 setitimer (ITIMER_REAL, &timerval, NULL);
1636 /* And disable the signal handler. */
1637 action.sa_handler = SIG_IGN;
1638 sigaction (SIGALRM, &action, NULL);
1642 notmuch_query_destroy (query);
1644 talloc_free (local);
1649 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1651 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1652 notmuch->atomic_nesting > 0)
1655 if (notmuch_database_needs_upgrade(notmuch))
1656 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1659 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1660 } catch (const Xapian::Error &error) {
1661 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1662 error.get_msg().c_str());
1663 notmuch->exception_reported = TRUE;
1664 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1668 notmuch->atomic_nesting++;
1669 return NOTMUCH_STATUS_SUCCESS;
1673 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1675 Xapian::WritableDatabase *db;
1677 if (notmuch->atomic_nesting == 0)
1678 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1680 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1681 notmuch->atomic_nesting > 1)
1684 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1686 db->commit_transaction ();
1688 /* This is a hack for testing. Xapian never flushes on a
1689 * non-flushed commit, even if the flush threshold is 1.
1690 * However, we rely on flushing to test atomicity. */
1691 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1692 if (thresh && atoi (thresh) == 1)
1694 } catch (const Xapian::Error &error) {
1695 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1696 error.get_msg().c_str());
1697 notmuch->exception_reported = TRUE;
1698 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1701 if (notmuch->atomic_dirty) {
1702 ++notmuch->revision;
1703 notmuch->atomic_dirty = FALSE;
1707 notmuch->atomic_nesting--;
1708 return NOTMUCH_STATUS_SUCCESS;
1712 notmuch_database_get_revision (notmuch_database_t *notmuch,
1716 *uuid = notmuch->uuid;
1717 return notmuch->revision;
1720 /* We allow the user to use arbitrarily long paths for directories. But
1721 * we have a term-length limit. So if we exceed that, we'll use the
1722 * SHA-1 of the path for the database term.
1724 * Note: This function may return the original value of 'path'. If it
1725 * does not, then the caller is responsible to free() the returned
1729 _notmuch_database_get_directory_db_path (const char *path)
1731 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1733 if (term_len > NOTMUCH_TERM_MAX)
1734 return _notmuch_sha1_of_string (path);
1739 /* Given a path, split it into two parts: the directory part is all
1740 * components except for the last, and the basename is that last
1741 * component. Getting the return-value for either part is optional
1742 * (the caller can pass NULL).
1744 * The original 'path' can represent either a regular file or a
1745 * directory---the splitting will be carried out in the same way in
1746 * either case. Trailing slashes on 'path' will be ignored, and any
1747 * cases of multiple '/' characters appearing in series will be
1748 * treated as a single '/'.
1750 * Allocation (if any) will have 'ctx' as the talloc owner. But
1751 * pointers will be returned within the original path string whenever
1754 * Note: If 'path' is non-empty and contains no non-trailing slash,
1755 * (that is, consists of a filename with no parent directory), then
1756 * the directory returned will be an empty string. However, if 'path'
1757 * is an empty string, then both directory and basename will be
1761 _notmuch_database_split_path (void *ctx,
1763 const char **directory,
1764 const char **basename)
1768 if (path == NULL || *path == '\0') {
1773 return NOTMUCH_STATUS_SUCCESS;
1776 /* Find the last slash (not counting a trailing slash), if any. */
1778 slash = path + strlen (path) - 1;
1780 /* First, skip trailing slashes. */
1781 while (slash != path && *slash == '/')
1784 /* Then, find a slash. */
1785 while (slash != path && *slash != '/') {
1792 /* Finally, skip multiple slashes. */
1793 while (slash != path && *(slash - 1) == '/')
1796 if (slash == path) {
1798 *directory = talloc_strdup (ctx, "");
1803 *directory = talloc_strndup (ctx, path, slash - path);
1806 return NOTMUCH_STATUS_SUCCESS;
1809 /* Find the document ID of the specified directory.
1811 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1812 * created if one does not exist for 'path'. Otherwise, if the
1813 * directory document does not exist, this sets *directory_id to
1814 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1817 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1819 notmuch_find_flags_t flags,
1820 unsigned int *directory_id)
1822 notmuch_directory_t *directory;
1823 notmuch_status_t status;
1827 return NOTMUCH_STATUS_SUCCESS;
1830 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1831 if (status || !directory) {
1836 *directory_id = _notmuch_directory_get_document_id (directory);
1838 notmuch_directory_destroy (directory);
1840 return NOTMUCH_STATUS_SUCCESS;
1844 _notmuch_database_get_directory_path (void *ctx,
1845 notmuch_database_t *notmuch,
1846 unsigned int doc_id)
1848 Xapian::Document document;
1850 document = find_document_for_doc_id (notmuch, doc_id);
1852 return talloc_strdup (ctx, document.get_data ().c_str ());
1855 /* Given a legal 'filename' for the database, (either relative to
1856 * database path or absolute with initial components identical to
1857 * database path), return a new string (with 'ctx' as the talloc
1858 * owner) suitable for use as a direntry term value.
1860 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1861 * will be created in the database as needed. Otherwise, if the
1862 * necessary directory documents do not exist, this sets
1863 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1866 _notmuch_database_filename_to_direntry (void *ctx,
1867 notmuch_database_t *notmuch,
1868 const char *filename,
1869 notmuch_find_flags_t flags,
1872 const char *relative, *directory, *basename;
1873 Xapian::docid directory_id;
1874 notmuch_status_t status;
1876 relative = _notmuch_database_relative_path (notmuch, filename);
1878 status = _notmuch_database_split_path (ctx, relative,
1879 &directory, &basename);
1883 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1885 if (status || directory_id == (unsigned int)-1) {
1890 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1892 return NOTMUCH_STATUS_SUCCESS;
1895 /* Given a legal 'path' for the database, return the relative path.
1897 * The return value will be a pointer to the original path contents,
1898 * and will be either the original string (if 'path' was relative) or
1899 * a portion of the string (if path was absolute and begins with the
1903 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1906 const char *db_path, *relative;
1907 unsigned int db_path_len;
1909 db_path = notmuch_database_get_path (notmuch);
1910 db_path_len = strlen (db_path);
1914 if (*relative == '/') {
1915 while (*relative == '/' && *(relative+1) == '/')
1918 if (strncmp (relative, db_path, db_path_len) == 0)
1920 relative += db_path_len;
1921 while (*relative == '/')
1930 notmuch_database_get_directory (notmuch_database_t *notmuch,
1932 notmuch_directory_t **directory)
1934 notmuch_status_t status;
1936 if (directory == NULL)
1937 return NOTMUCH_STATUS_NULL_POINTER;
1941 *directory = _notmuch_directory_create (notmuch, path,
1942 NOTMUCH_FIND_LOOKUP, &status);
1943 } catch (const Xapian::Error &error) {
1944 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1945 error.get_msg().c_str());
1946 notmuch->exception_reported = TRUE;
1947 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1952 /* Allocate a document ID that satisfies the following criteria:
1954 * 1. The ID does not exist for any document in the Xapian database
1956 * 2. The ID was not previously returned from this function
1958 * 3. The ID is the smallest integer satisfying (1) and (2)
1960 * This function will trigger an internal error if these constraints
1961 * cannot all be satisfied, (that is, the pool of available document
1962 * IDs has been exhausted).
1965 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1967 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1969 notmuch->last_doc_id++;
1971 if (notmuch->last_doc_id == 0)
1972 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1974 return notmuch->last_doc_id;
1978 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1980 /* 16 bytes (+ terminator) for hexadecimal representation of
1981 * a 64-bit integer. */
1982 static char thread_id[17];
1983 Xapian::WritableDatabase *db;
1985 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1987 notmuch->last_thread_id++;
1989 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1991 db->set_metadata ("last_thread_id", thread_id);
1997 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1999 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2000 message_id = _notmuch_message_id_compressed (ctx, message_id);
2002 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2006 static notmuch_status_t
2007 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2009 const char *message_id,
2010 const char **thread_id_ret);
2012 /* Find the thread ID to which the message with 'message_id' belongs.
2014 * Note: 'thread_id_ret' must not be NULL!
2015 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2018 * Note: If there is no message in the database with the given
2019 * 'message_id' then a new thread_id will be allocated for this
2020 * message ID and stored in the database metadata so that the
2021 * thread ID can be looked up if the message is added to the database
2024 static notmuch_status_t
2025 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2027 const char *message_id,
2028 const char **thread_id_ret)
2030 notmuch_private_status_t status;
2031 notmuch_message_t *message;
2033 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2034 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2037 /* Look for this message (regular or ghost) */
2038 message = _notmuch_message_create_for_message_id (
2039 notmuch, message_id, &status);
2040 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2041 /* Message exists */
2042 *thread_id_ret = talloc_steal (
2043 ctx, notmuch_message_get_thread_id (message));
2044 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2045 /* Message did not exist. Give it a fresh thread ID and
2046 * populate this message as a ghost message. */
2047 *thread_id_ret = talloc_strdup (
2048 ctx, _notmuch_database_generate_thread_id (notmuch));
2049 if (! *thread_id_ret) {
2050 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2052 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2054 /* Commit the new ghost message */
2055 _notmuch_message_sync (message);
2058 /* Create failed. Fall through. */
2061 notmuch_message_destroy (message);
2063 return COERCE_STATUS (status, "Error creating ghost message");
2066 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2067 static notmuch_status_t
2068 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2070 const char *message_id,
2071 const char **thread_id_ret)
2073 notmuch_status_t status;
2074 notmuch_message_t *message;
2075 string thread_id_string;
2077 Xapian::WritableDatabase *db;
2079 status = notmuch_database_find_message (notmuch, message_id, &message);
2085 *thread_id_ret = talloc_steal (ctx,
2086 notmuch_message_get_thread_id (message));
2088 notmuch_message_destroy (message);
2090 return NOTMUCH_STATUS_SUCCESS;
2093 /* Message has not been seen yet.
2095 * We may have seen a reference to it already, in which case, we
2096 * can return the thread ID stored in the metadata. Otherwise, we
2097 * generate a new thread ID and store it there.
2099 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2100 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2101 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2103 if (thread_id_string.empty()) {
2104 *thread_id_ret = talloc_strdup (ctx,
2105 _notmuch_database_generate_thread_id (notmuch));
2106 db->set_metadata (metadata_key, *thread_id_ret);
2108 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2111 talloc_free (metadata_key);
2113 return NOTMUCH_STATUS_SUCCESS;
2116 static notmuch_status_t
2117 _merge_threads (notmuch_database_t *notmuch,
2118 const char *winner_thread_id,
2119 const char *loser_thread_id)
2121 Xapian::PostingIterator loser, loser_end;
2122 notmuch_message_t *message = NULL;
2123 notmuch_private_status_t private_status;
2124 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2126 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2128 for ( ; loser != loser_end; loser++) {
2129 message = _notmuch_message_create (notmuch, notmuch,
2130 *loser, &private_status);
2131 if (message == NULL) {
2132 ret = COERCE_STATUS (private_status,
2133 "Cannot find document for doc_id from query");
2137 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2138 _notmuch_message_add_term (message, "thread", winner_thread_id);
2139 _notmuch_message_sync (message);
2141 notmuch_message_destroy (message);
2147 notmuch_message_destroy (message);
2153 _my_talloc_free_for_g_hash (void *ptr)
2158 static notmuch_status_t
2159 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2160 notmuch_message_t *message,
2161 notmuch_message_file_t *message_file,
2162 const char **thread_id)
2164 GHashTable *parents = NULL;
2165 const char *refs, *in_reply_to, *in_reply_to_message_id;
2166 const char *last_ref_message_id, *this_message_id;
2167 GList *l, *keys = NULL;
2168 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2170 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2171 _my_talloc_free_for_g_hash, NULL);
2172 this_message_id = notmuch_message_get_message_id (message);
2174 refs = _notmuch_message_file_get_header (message_file, "references");
2175 last_ref_message_id = parse_references (message,
2179 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2180 in_reply_to_message_id = parse_references (message,
2182 parents, in_reply_to);
2184 /* For the parent of this message, use the last message ID of the
2185 * References header, if available. If not, fall back to the
2186 * first message ID in the In-Reply-To header. */
2187 if (last_ref_message_id) {
2188 _notmuch_message_add_term (message, "replyto",
2189 last_ref_message_id);
2190 } else if (in_reply_to_message_id) {
2191 _notmuch_message_add_term (message, "replyto",
2192 in_reply_to_message_id);
2195 keys = g_hash_table_get_keys (parents);
2196 for (l = keys; l; l = l->next) {
2197 char *parent_message_id;
2198 const char *parent_thread_id = NULL;
2200 parent_message_id = (char *) l->data;
2202 _notmuch_message_add_term (message, "reference",
2205 ret = _resolve_message_id_to_thread_id (notmuch,
2212 if (*thread_id == NULL) {
2213 *thread_id = talloc_strdup (message, parent_thread_id);
2214 _notmuch_message_add_term (message, "thread", *thread_id);
2215 } else if (strcmp (*thread_id, parent_thread_id)) {
2216 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2226 g_hash_table_unref (parents);
2231 static notmuch_status_t
2232 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2233 notmuch_message_t *message,
2234 const char **thread_id)
2236 const char *message_id = notmuch_message_get_message_id (message);
2237 Xapian::PostingIterator child, children_end;
2238 notmuch_message_t *child_message = NULL;
2239 const char *child_thread_id;
2240 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2241 notmuch_private_status_t private_status;
2243 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2245 for ( ; child != children_end; child++) {
2247 child_message = _notmuch_message_create (message, notmuch,
2248 *child, &private_status);
2249 if (child_message == NULL) {
2250 ret = COERCE_STATUS (private_status,
2251 "Cannot find document for doc_id from query");
2255 child_thread_id = notmuch_message_get_thread_id (child_message);
2256 if (*thread_id == NULL) {
2257 *thread_id = talloc_strdup (message, child_thread_id);
2258 _notmuch_message_add_term (message, "thread", *thread_id);
2259 } else if (strcmp (*thread_id, child_thread_id)) {
2260 _notmuch_message_remove_term (child_message, "reference",
2262 _notmuch_message_sync (child_message);
2263 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2268 notmuch_message_destroy (child_message);
2269 child_message = NULL;
2274 notmuch_message_destroy (child_message);
2279 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2281 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2282 notmuch_message_t *message)
2284 const char *message_id;
2288 message_id = notmuch_message_get_message_id (message);
2289 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2291 /* Check if we have already seen related messages to this one.
2292 * If we have then use the thread_id that we stored at that time.
2294 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2295 if (stored_id.empty ()) {
2298 Xapian::WritableDatabase *db;
2300 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2302 /* Clear the metadata for this message ID. We don't need it
2304 db->set_metadata (metadata_key, "");
2306 return talloc_strdup (ctx, stored_id.c_str ());
2310 /* Given a blank or ghost 'message' and its corresponding
2311 * 'message_file' link it to existing threads in the database.
2313 * First, if is_ghost, this retrieves the thread ID already stored in
2314 * the message (which will be the case if a message was previously
2315 * added that referenced this one). If the message is blank
2316 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2317 * later in this function). If the database does not support ghost
2318 * messages, this checks for a thread ID stored in database metadata
2319 * for this message ID.
2321 * Second, we look at 'message_file' and its link-relevant headers
2322 * (References and In-Reply-To) for message IDs.
2324 * Finally, we look in the database for existing message that
2325 * reference 'message'.
2327 * In all cases, we assign to the current message the first thread ID
2328 * found. We will also merge any existing, distinct threads where this
2329 * message belongs to both, (which is not uncommon when messages are
2330 * processed out of order).
2332 * Finally, if no thread ID has been found through referenced messages, we
2333 * call _notmuch_message_generate_thread_id to generate a new thread
2334 * ID. This should only happen for new, top-level messages, (no
2335 * References or In-Reply-To header in this message, and no previously
2336 * added message refers to this message).
2338 static notmuch_status_t
2339 _notmuch_database_link_message (notmuch_database_t *notmuch,
2340 notmuch_message_t *message,
2341 notmuch_message_file_t *message_file,
2342 notmuch_bool_t is_ghost)
2344 void *local = talloc_new (NULL);
2345 notmuch_status_t status;
2346 const char *thread_id = NULL;
2348 /* Check if the message already had a thread ID */
2349 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2351 thread_id = notmuch_message_get_thread_id (message);
2353 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2355 _notmuch_message_add_term (message, "thread", thread_id);
2358 status = _notmuch_database_link_message_to_parents (notmuch, message,
2364 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2365 /* In general, it shouldn't be necessary to link children,
2366 * since the earlier indexing of those children will have
2367 * stored a thread ID for the missing parent. However, prior
2368 * to ghost messages, these stored thread IDs were NOT
2369 * rewritten during thread merging (and there was no
2370 * performant way to do so), so if indexed children were
2371 * pulled into a different thread ID by a merge, it was
2372 * necessary to pull them *back* into the stored thread ID of
2373 * the parent. With ghost messages, we just rewrite the
2374 * stored thread IDs during merging, so this workaround isn't
2376 status = _notmuch_database_link_message_to_children (notmuch, message,
2382 /* If not part of any existing thread, generate a new thread ID. */
2383 if (thread_id == NULL) {
2384 thread_id = _notmuch_database_generate_thread_id (notmuch);
2386 _notmuch_message_add_term (message, "thread", thread_id);
2390 talloc_free (local);
2396 notmuch_database_add_message (notmuch_database_t *notmuch,
2397 const char *filename,
2398 notmuch_message_t **message_ret)
2400 notmuch_message_file_t *message_file;
2401 notmuch_message_t *message = NULL;
2402 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2403 notmuch_private_status_t private_status;
2404 notmuch_bool_t is_ghost = false;
2406 const char *date, *header;
2407 const char *from, *to, *subject;
2408 char *message_id = NULL;
2411 *message_ret = NULL;
2413 ret = _notmuch_database_ensure_writable (notmuch);
2417 message_file = _notmuch_message_file_open (notmuch, filename);
2418 if (message_file == NULL)
2419 return NOTMUCH_STATUS_FILE_ERROR;
2421 /* Adding a message may change many documents. Do this all
2423 ret = notmuch_database_begin_atomic (notmuch);
2427 /* Parse message up front to get better error status. */
2428 ret = _notmuch_message_file_parse (message_file);
2433 /* Before we do any real work, (especially before doing a
2434 * potential SHA-1 computation on the entire file's contents),
2435 * let's make sure that what we're looking at looks like an
2436 * actual email message.
2438 from = _notmuch_message_file_get_header (message_file, "from");
2439 subject = _notmuch_message_file_get_header (message_file, "subject");
2440 to = _notmuch_message_file_get_header (message_file, "to");
2442 if ((from == NULL || *from == '\0') &&
2443 (subject == NULL || *subject == '\0') &&
2444 (to == NULL || *to == '\0'))
2446 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2450 /* Now that we're sure it's mail, the first order of business
2451 * is to find a message ID (or else create one ourselves). */
2453 header = _notmuch_message_file_get_header (message_file, "message-id");
2454 if (header && *header != '\0') {
2455 message_id = _parse_message_id (message_file, header, NULL);
2457 /* So the header value isn't RFC-compliant, but it's
2458 * better than no message-id at all. */
2459 if (message_id == NULL)
2460 message_id = talloc_strdup (message_file, header);
2463 if (message_id == NULL ) {
2464 /* No message-id at all, let's generate one by taking a
2465 * hash over the file's contents. */
2466 char *sha1 = _notmuch_sha1_of_file (filename);
2468 /* If that failed too, something is really wrong. Give up. */
2470 ret = NOTMUCH_STATUS_FILE_ERROR;
2474 message_id = talloc_asprintf (message_file,
2475 "notmuch-sha1-%s", sha1);
2479 /* Now that we have a message ID, we get a message object,
2480 * (which may or may not reference an existing document in the
2483 message = _notmuch_message_create_for_message_id (notmuch,
2487 talloc_free (message_id);
2489 if (message == NULL) {
2490 ret = COERCE_STATUS (private_status,
2491 "Unexpected status value from _notmuch_message_create_for_message_id");
2495 _notmuch_message_add_filename (message, filename);
2497 /* Is this a newly created message object or a ghost
2498 * message? We have to be slightly careful: if this is a
2499 * blank message, it's not safe to call
2500 * notmuch_message_get_flag yet. */
2501 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2502 (is_ghost = notmuch_message_get_flag (
2503 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2504 _notmuch_message_add_term (message, "type", "mail");
2506 /* Convert ghost message to a regular message */
2507 _notmuch_message_remove_term (message, "type", "ghost");
2509 ret = _notmuch_database_link_message (notmuch, message,
2510 message_file, is_ghost);
2514 date = _notmuch_message_file_get_header (message_file, "date");
2515 _notmuch_message_set_header_values (message, date, from, subject);
2517 ret = _notmuch_message_index_file (message, message_file);
2521 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2524 _notmuch_message_sync (message);
2525 } catch (const Xapian::Error &error) {
2526 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2527 error.get_msg().c_str());
2528 notmuch->exception_reported = TRUE;
2529 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2535 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2536 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2537 *message_ret = message;
2539 notmuch_message_destroy (message);
2543 _notmuch_message_file_close (message_file);
2545 ret2 = notmuch_database_end_atomic (notmuch);
2546 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2547 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2548 ret2 != NOTMUCH_STATUS_SUCCESS)
2555 notmuch_database_remove_message (notmuch_database_t *notmuch,
2556 const char *filename)
2558 notmuch_status_t status;
2559 notmuch_message_t *message;
2561 status = notmuch_database_find_message_by_filename (notmuch, filename,
2564 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2565 status = _notmuch_message_remove_filename (message, filename);
2566 if (status == NOTMUCH_STATUS_SUCCESS)
2567 _notmuch_message_delete (message);
2568 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2569 _notmuch_message_sync (message);
2571 notmuch_message_destroy (message);
2578 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2579 const char *filename,
2580 notmuch_message_t **message_ret)
2583 const char *prefix = _find_prefix ("file-direntry");
2584 char *direntry, *term;
2585 Xapian::PostingIterator i, end;
2586 notmuch_status_t status;
2588 if (message_ret == NULL)
2589 return NOTMUCH_STATUS_NULL_POINTER;
2591 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2592 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2594 /* return NULL on any failure */
2595 *message_ret = NULL;
2597 local = talloc_new (notmuch);
2600 status = _notmuch_database_filename_to_direntry (
2601 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2602 if (status || !direntry)
2605 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2607 find_doc_ids_for_term (notmuch, term, &i, &end);
2610 notmuch_private_status_t private_status;
2612 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2614 if (*message_ret == NULL)
2615 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2617 } catch (const Xapian::Error &error) {
2618 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2619 error.get_msg().c_str());
2620 notmuch->exception_reported = TRUE;
2621 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2625 talloc_free (local);
2627 if (status && *message_ret) {
2628 notmuch_message_destroy (*message_ret);
2629 *message_ret = NULL;
2634 notmuch_string_list_t *
2635 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2636 Xapian::TermIterator &end,
2639 int prefix_len = strlen (prefix);
2640 notmuch_string_list_t *list;
2642 list = _notmuch_string_list_create (ctx);
2643 if (unlikely (list == NULL))
2646 for (i.skip_to (prefix); i != end; i++) {
2647 /* Terminate loop at first term without desired prefix. */
2648 if (strncmp ((*i).c_str (), prefix, prefix_len))
2651 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2658 notmuch_database_get_all_tags (notmuch_database_t *db)
2660 Xapian::TermIterator i, end;
2661 notmuch_string_list_t *tags;
2664 i = db->xapian_db->allterms_begin();
2665 end = db->xapian_db->allterms_end();
2666 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2667 _find_prefix ("tag"));
2668 _notmuch_string_list_sort (tags);
2669 return _notmuch_tags_create (db, tags);
2670 } catch (const Xapian::Error &error) {
2671 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2672 error.get_msg().c_str());
2673 db->exception_reported = TRUE;
2679 notmuch_database_status_string (const notmuch_database_t *notmuch)
2681 return notmuch->status_string;