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 http://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
23 #include "string-util.h"
32 #include <glib.h> /* g_free, GPtrArray, GHashTable */
33 #include <glib-object.h> /* g_type_init */
35 #include <gmime/gmime.h> /* g_mime_init */
39 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46 #define NOTMUCH_DATABASE_VERSION 3
48 #define STRINGIFY(s) _SUB_STRINGIFY(s)
49 #define _SUB_STRINGIFY(s) #s
51 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
53 * We currently have three different types of documents (mail, ghost,
54 * and directory) and also some metadata.
58 * A mail document is associated with a particular email message. It
59 * is stored in one or more files on disk (though only one has its
60 * content indexed) and is uniquely identified by its "id" field
61 * (which is generally the message ID). It is indexed with the
62 * following prefixed terms which the database uses to construct
65 * Single terms of given prefix:
69 * id: Unique ID of mail. This is from the Message-ID header
70 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
71 * If it's present and too long, then we use
72 * "notmuch-sha1-<sha1_sum_of_message_id>".
73 * If this header is not present, we use
74 * "notmuch-sha1-<sha1_sum_of_entire_file>".
76 * thread: The ID of the thread to which the mail belongs
78 * replyto: The ID from the In-Reply-To header of the mail (if any).
80 * Multiple terms of given prefix:
82 * reference: All message IDs from In-Reply-To and References
83 * headers in the message.
85 * tag: Any tags associated with this message by the user.
87 * file-direntry: A colon-separated pair of values
88 * (INTEGER:STRING), where INTEGER is the
89 * document ID of a directory document, and
90 * STRING is the name of a file within that
91 * directory for this mail message.
93 * A mail document also has four values:
95 * TIMESTAMP: The time_t value corresponding to the message's
98 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
100 * FROM: The value of the "From" header
102 * SUBJECT: The value of the "Subject" header
104 * LAST_MOD: The revision number as of the last tag or
107 * In addition, terms from the content of the message are added with
108 * "from", "to", "attachment", and "subject" prefixes for use by the
109 * user in searching. Similarly, terms from the path of the mail
110 * message are added with "folder" and "path" prefixes. But the
111 * database doesn't really care itself about any of these.
113 * The data portion of a mail document is empty.
115 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
116 * -----------------------------------------------
117 * A ghost mail document is like a mail document, but where we don't
118 * have the message content. These are used to track thread reference
119 * information for messages we haven't received.
121 * A ghost mail document has type: ghost; id and thread fields that
122 * are identical to the mail document fields; and a MESSAGE_ID value.
126 * A directory document is used by a client of the notmuch library to
127 * maintain data necessary to allow for efficient polling of mail
130 * All directory documents contain one term:
132 * directory: The directory path (relative to the database path)
133 * Or the SHA1 sum of the directory path (if the
134 * path itself is too long to fit in a Xapian
137 * And all directory documents for directories other than top-level
138 * directories also contain the following term:
140 * directory-direntry: A colon-separated pair of values
141 * (INTEGER:STRING), where INTEGER is the
142 * document ID of the parent directory
143 * document, and STRING is the name of this
144 * directory within that parent.
146 * All directory documents have a single value:
148 * TIMESTAMP: The mtime of the directory (at last scan)
150 * The data portion of a directory document contains the path of the
151 * directory (relative to the database path).
155 * Xapian allows us to store arbitrary name-value pairs as
156 * "metadata". We currently use the following metadata names with the
159 * version The database schema version, (which is distinct
160 * from both the notmuch package version (see
161 * notmuch --version) and the libnotmuch library
162 * version. The version is stored as an base-10
163 * ASCII integer. The initial database version
164 * was 1, (though a schema existed before that
165 * were no "version" database value existed at
166 * all). Successive versions are allocated as
167 * changes are made to the database (such as by
168 * indexing new fields).
170 * features The set of features supported by this
171 * database. This consists of a set of
172 * '\n'-separated lines, where each is a feature
173 * name, a '\t', and compatibility flags. If the
174 * compatibility flags contain 'w', then the
175 * opener must support this feature to safely
176 * write this database. If the compatibility
177 * flags contain 'r', then the opener must
178 * support this feature to read this database.
179 * Introduced in database version 3.
181 * last_thread_id The last thread ID generated. This is stored
182 * as a 16-byte hexadecimal ASCII representation
183 * of a 64-bit unsigned integer. The first ID
184 * generated is 1 and the value will be
185 * incremented for each thread ID.
190 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
191 * Instead, the database has the following additional database
194 * thread_id_* A pre-allocated thread ID for a particular
195 * message. This is actually an arbitrarily large
196 * family of metadata name. Any particular name is
197 * formed by concatenating "thread_id_" with a message
198 * ID (or the SHA1 sum of a message ID if it is very
199 * long---see description of 'id' in the mail
200 * document). The value stored is a thread ID.
202 * These thread ID metadata values are stored
203 * whenever a message references a parent message
204 * that does not yet exist in the database. A
205 * thread ID will be allocated and stored, and if
206 * the message is later added, the stored thread
207 * ID will be used (and the metadata value will
210 * Even before a message is added, it's
211 * pre-allocated thread ID is useful so that all
212 * descendant messages that reference this common
213 * parent can be recognized as belonging to the
217 /* With these prefix values we follow the conventions published here:
219 * http://xapian.org/docs/omega/termprefixes.html
221 * as much as makes sense. Note that I took some liberty in matching
222 * the reserved prefix values to notmuch concepts, (for example, 'G'
223 * is documented as "newsGroup (or similar entity - e.g. a web forum
224 * name)", for which I think the thread is the closest analogue in
225 * notmuch. This in spite of the fact that we will eventually be
226 * storing mailing-list messages where 'G' for "mailing list name"
227 * might be even a closer analogue. I'm treating the single-character
228 * prefixes preferentially for core notmuch concepts (which will be
229 * nearly universal to all mail messages).
232 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
234 { "reference", "XREFERENCE" },
235 { "replyto", "XREPLYTO" },
236 { "directory", "XDIRECTORY" },
237 { "file-direntry", "XFDIRENTRY" },
238 { "directory-direntry", "XDDIRENTRY" },
241 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
248 * Without the ":", since this is a multi-letter prefix, Xapian
249 * will add a colon itself if the first letter of the path is
250 * upper-case ASCII. Including the ":" forces there to always be a
251 * colon, which keeps our own logic simpler.
253 { "folder", "XFOLDER:" },
256 static prefix_t PROBABILISTIC_PREFIX[]= {
259 { "attachment", "XATTACHMENT" },
260 { "mimetype", "XMIMETYPE"},
261 { "subject", "XSUBJECT"},
265 _find_prefix (const char *name)
269 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
270 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
271 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
274 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
275 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
276 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
279 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
280 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
281 return PROBABILISTIC_PREFIX[i].prefix;
284 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
289 static const struct {
290 /* NOTMUCH_FEATURE_* value. */
291 _notmuch_features value;
292 /* Feature name as it appears in the database. This name should
293 * be appropriate for displaying to the user if an older version
294 * of notmuch doesn't support this feature. */
296 /* Compatibility flags when this feature is declared. */
298 } feature_names[] = {
299 { NOTMUCH_FEATURE_FILE_TERMS,
300 "multiple paths per message", "rw" },
301 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
302 "relative directory paths", "rw" },
303 /* Header values are not required for reading a database because a
304 * reader can just refer to the message file. */
305 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
306 "from/subject/message-ID in database", "w" },
307 { NOTMUCH_FEATURE_BOOL_FOLDER,
308 "exact folder:/path: search", "rw" },
309 { NOTMUCH_FEATURE_GHOSTS,
310 "mail documents for missing messages", "w"},
311 /* Knowledge of the index mime-types are not required for reading
312 * a database because a reader will just be unable to query
314 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
315 "indexed MIME types", "w"},
316 { NOTMUCH_FEATURE_LAST_MOD,
317 "modification tracking", "w"},
321 notmuch_status_to_string (notmuch_status_t status)
324 case NOTMUCH_STATUS_SUCCESS:
325 return "No error occurred";
326 case NOTMUCH_STATUS_OUT_OF_MEMORY:
327 return "Out of memory";
328 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
329 return "Attempt to write to a read-only database";
330 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
331 return "A Xapian exception occurred";
332 case NOTMUCH_STATUS_FILE_ERROR:
333 return "Something went wrong trying to read or write a file";
334 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
335 return "File is not an email";
336 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
337 return "Message ID is identical to a message in database";
338 case NOTMUCH_STATUS_NULL_POINTER:
339 return "Erroneous NULL pointer";
340 case NOTMUCH_STATUS_TAG_TOO_LONG:
341 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
342 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
343 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
344 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
345 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
346 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
347 return "Unsupported operation";
348 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
349 return "Operation requires a database upgrade";
350 case NOTMUCH_STATUS_PATH_ERROR:
351 return "Path supplied is illegal for this function";
353 case NOTMUCH_STATUS_LAST_STATUS:
354 return "Unknown error status value";
359 _notmuch_database_log (notmuch_database_t *notmuch,
365 va_start (va_args, format);
367 if (notmuch->status_string)
368 talloc_free (notmuch->status_string);
370 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
376 find_doc_ids_for_term (notmuch_database_t *notmuch,
378 Xapian::PostingIterator *begin,
379 Xapian::PostingIterator *end)
381 *begin = notmuch->xapian_db->postlist_begin (term);
383 *end = notmuch->xapian_db->postlist_end (term);
387 find_doc_ids (notmuch_database_t *notmuch,
388 const char *prefix_name,
390 Xapian::PostingIterator *begin,
391 Xapian::PostingIterator *end)
395 term = talloc_asprintf (notmuch, "%s%s",
396 _find_prefix (prefix_name), value);
398 find_doc_ids_for_term (notmuch, term, begin, end);
403 notmuch_private_status_t
404 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
405 const char *prefix_name,
407 unsigned int *doc_id)
409 Xapian::PostingIterator i, end;
411 find_doc_ids (notmuch, prefix_name, value, &i, &end);
415 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
420 #if DEBUG_DATABASE_SANITY
424 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
428 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
431 static Xapian::Document
432 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
434 return notmuch->xapian_db->get_document (doc_id);
437 /* Generate a compressed version of 'message_id' of the form:
439 * notmuch-sha1-<sha1_sum_of_message_id>
442 _notmuch_message_id_compressed (void *ctx, const char *message_id)
444 char *sha1, *compressed;
446 sha1 = _notmuch_sha1_of_string (message_id);
448 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
455 notmuch_database_find_message (notmuch_database_t *notmuch,
456 const char *message_id,
457 notmuch_message_t **message_ret)
459 notmuch_private_status_t status;
462 if (message_ret == NULL)
463 return NOTMUCH_STATUS_NULL_POINTER;
465 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
466 message_id = _notmuch_message_id_compressed (notmuch, message_id);
469 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
470 message_id, &doc_id);
472 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
475 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
477 if (*message_ret == NULL)
478 return NOTMUCH_STATUS_OUT_OF_MEMORY;
481 return NOTMUCH_STATUS_SUCCESS;
482 } catch (const Xapian::Error &error) {
483 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
484 error.get_msg().c_str());
485 notmuch->exception_reported = TRUE;
487 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
491 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
492 * a (potentially nested) parenthesized sequence with '\' used to
493 * escape any character (including parentheses).
495 * If the sequence to be skipped continues to the end of the string,
496 * then 'str' will be left pointing at the final terminating '\0'
500 skip_space_and_comments (const char **str)
505 while (*s && (isspace (*s) || *s == '(')) {
506 while (*s && isspace (*s))
511 while (*s && nesting) {
514 } else if (*s == ')') {
516 } else if (*s == '\\') {
528 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
529 * comments, and the '<' and '>' delimiters.
531 * If not NULL, then *next will be made to point to the first character
532 * not parsed, (possibly pointing to the final '\0' terminator.
534 * Returns a newly talloc'ed string belonging to 'ctx'.
536 * Returns NULL if there is any error parsing the message-id. */
538 _parse_message_id (void *ctx, const char *message_id, const char **next)
543 if (message_id == NULL || *message_id == '\0')
548 skip_space_and_comments (&s);
550 /* Skip any unstructured text as well. */
551 while (*s && *s != '<')
562 skip_space_and_comments (&s);
565 while (*end && *end != '>')
574 if (end > s && *end == '>')
579 result = talloc_strndup (ctx, s, end - s + 1);
581 /* Finally, collapse any whitespace that is within the message-id
587 for (r = result, len = strlen (r); *r; r++, len--)
588 if (*r == ' ' || *r == '\t')
589 memmove (r, r+1, len);
595 /* Parse a References header value, putting a (talloc'ed under 'ctx')
596 * copy of each referenced message-id into 'hash'.
598 * We explicitly avoid including any reference identical to
599 * 'message_id' in the result (to avoid mass confusion when a single
600 * message references itself cyclically---and yes, mail messages are
601 * not infrequent in the wild that do this---don't ask me why).
603 * Return the last reference parsed, if it is not equal to message_id.
606 parse_references (void *ctx,
607 const char *message_id,
611 char *ref, *last_ref = NULL;
613 if (refs == NULL || *refs == '\0')
617 ref = _parse_message_id (ctx, refs, &refs);
619 if (ref && strcmp (ref, message_id)) {
620 g_hash_table_insert (hash, ref, NULL);
625 /* The return value of this function is used to add a parent
626 * reference to the database. We should avoid making a message
627 * its own parent, thus the above check.
633 notmuch_database_create (const char *path, notmuch_database_t **database)
635 char *status_string = NULL;
636 notmuch_status_t status;
638 status = notmuch_database_create_verbose (path, database,
642 fputs (status_string, stderr);
643 free (status_string);
650 notmuch_database_create_verbose (const char *path,
651 notmuch_database_t **database,
652 char **status_string)
654 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
655 notmuch_database_t *notmuch = NULL;
656 char *notmuch_path = NULL;
657 char *message = NULL;
662 message = strdup ("Error: Cannot create a database for a NULL path.\n");
663 status = NOTMUCH_STATUS_NULL_POINTER;
667 if (path[0] != '/') {
668 message = strdup ("Error: Database path must be absolute.\n");
669 status = NOTMUCH_STATUS_PATH_ERROR;
673 err = stat (path, &st);
675 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
676 path, strerror (errno)));
677 status = NOTMUCH_STATUS_FILE_ERROR;
681 if (! S_ISDIR (st.st_mode)) {
682 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
683 "Not a directory.\n",
685 status = NOTMUCH_STATUS_FILE_ERROR;
689 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
691 err = mkdir (notmuch_path, 0755);
694 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
695 notmuch_path, strerror (errno)));
696 status = NOTMUCH_STATUS_FILE_ERROR;
700 status = notmuch_database_open_verbose (path,
701 NOTMUCH_DATABASE_MODE_READ_WRITE,
706 /* Upgrade doesn't add these feature to existing databases, but
707 * new databases have them. */
708 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
709 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
711 status = notmuch_database_upgrade (notmuch, NULL, NULL);
713 notmuch_database_close(notmuch);
719 talloc_free (notmuch_path);
723 *status_string = message;
730 talloc_free (notmuch);
735 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
737 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
738 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
739 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
742 return NOTMUCH_STATUS_SUCCESS;
745 /* Allocate a revision number for the next change. */
747 _notmuch_database_new_revision (notmuch_database_t *notmuch)
749 unsigned long new_revision = notmuch->revision + 1;
751 /* If we're in an atomic section, hold off on updating the
752 * committed revision number until we commit the atomic section.
754 if (notmuch->atomic_nesting)
755 notmuch->atomic_dirty = TRUE;
757 notmuch->revision = new_revision;
762 /* Parse a database features string from the given database version.
763 * Returns the feature bit set.
765 * For version < 3, this ignores the features string and returns a
766 * hard-coded set of features.
768 * If there are unrecognized features that are required to open the
769 * database in mode (which should be 'r' or 'w'), return a
770 * comma-separated list of unrecognized but required features in
771 * *incompat_out suitable for presenting to the user. *incompat_out
772 * will be allocated from ctx.
774 static _notmuch_features
775 _parse_features (const void *ctx, const char *features, unsigned int version,
776 char mode, char **incompat_out)
778 _notmuch_features res = static_cast<_notmuch_features>(0);
779 unsigned int namelen, i;
783 /* Prior to database version 3, features were implied by the
786 return NOTMUCH_FEATURES_V0;
787 else if (version == 1)
788 return NOTMUCH_FEATURES_V1;
789 else if (version == 2)
790 return NOTMUCH_FEATURES_V2;
792 /* Parse the features string */
793 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
794 flags = strchr (features, '\t');
795 if (! flags || flags > features + llen)
797 namelen = flags - features;
799 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
800 if (strlen (feature_names[i].name) == namelen &&
801 strncmp (feature_names[i].name, features, namelen) == 0) {
802 res |= feature_names[i].value;
807 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
808 /* Unrecognized feature */
809 const char *have = strchr (flags, mode);
810 if (have && have < features + llen) {
811 /* This feature is required to access this database in
812 * 'mode', but we don't understand it. */
814 *incompat_out = talloc_strdup (ctx, "");
815 *incompat_out = talloc_asprintf_append_buffer (
816 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
826 _print_features (const void *ctx, unsigned int features)
829 char *res = talloc_strdup (ctx, "");
831 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
832 if (features & feature_names[i].value)
833 res = talloc_asprintf_append_buffer (
834 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
840 notmuch_database_open (const char *path,
841 notmuch_database_mode_t mode,
842 notmuch_database_t **database)
844 char *status_string = NULL;
845 notmuch_status_t status;
847 status = notmuch_database_open_verbose (path, mode, database,
851 fputs (status_string, stderr);
852 free (status_string);
859 notmuch_database_open_verbose (const char *path,
860 notmuch_database_mode_t mode,
861 notmuch_database_t **database,
862 char **status_string)
864 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
865 void *local = talloc_new (NULL);
866 notmuch_database_t *notmuch = NULL;
867 char *notmuch_path, *xapian_path, *incompat_features;
868 char *message = NULL;
871 unsigned int i, version;
872 static int initialized = 0;
875 message = strdup ("Error: Cannot open a database for a NULL path.\n");
876 status = NOTMUCH_STATUS_NULL_POINTER;
880 if (path[0] != '/') {
881 message = strdup ("Error: Database path must be absolute.\n");
882 status = NOTMUCH_STATUS_PATH_ERROR;
886 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
887 message = strdup ("Out of memory\n");
888 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
892 err = stat (notmuch_path, &st);
894 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
895 notmuch_path, strerror (errno)));
896 status = NOTMUCH_STATUS_FILE_ERROR;
900 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
901 message = strdup ("Out of memory\n");
902 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
906 /* Initialize the GLib type system and threads */
907 #if !GLIB_CHECK_VERSION(2, 35, 1)
911 /* Initialize gmime */
913 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
917 notmuch = talloc_zero (NULL, notmuch_database_t);
918 notmuch->exception_reported = FALSE;
919 notmuch->status_string = NULL;
920 notmuch->path = talloc_strdup (notmuch, path);
922 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
923 notmuch->path[strlen (notmuch->path) - 1] = '\0';
925 notmuch->mode = mode;
926 notmuch->atomic_nesting = 0;
928 string last_thread_id;
931 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
932 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
933 Xapian::DB_CREATE_OR_OPEN);
935 notmuch->xapian_db = new Xapian::Database (xapian_path);
938 /* Check version. As of database version 3, we represent
939 * changes in terms of features, so assume a version bump
940 * means a dramatically incompatible change. */
941 version = notmuch_database_get_version (notmuch);
942 if (version > NOTMUCH_DATABASE_VERSION) {
943 IGNORE_RESULT (asprintf (&message,
944 "Error: Notmuch database at %s\n"
945 " has a newer database format version (%u) than supported by this\n"
946 " version of notmuch (%u).\n",
947 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
948 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
949 notmuch_database_destroy (notmuch);
951 status = NOTMUCH_STATUS_FILE_ERROR;
955 /* Check features. */
956 incompat_features = NULL;
957 notmuch->features = _parse_features (
958 local, notmuch->xapian_db->get_metadata ("features").c_str (),
959 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
961 if (incompat_features) {
962 IGNORE_RESULT (asprintf (&message,
963 "Error: Notmuch database at %s\n"
964 " requires features (%s)\n"
965 " not supported by this version of notmuch.\n",
966 notmuch_path, incompat_features));
967 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
968 notmuch_database_destroy (notmuch);
970 status = NOTMUCH_STATUS_FILE_ERROR;
974 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
975 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
976 if (last_thread_id.empty ()) {
977 notmuch->last_thread_id = 0;
982 str = last_thread_id.c_str ();
983 notmuch->last_thread_id = strtoull (str, &end, 16);
985 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
988 /* Get current highest revision number. */
989 last_mod = notmuch->xapian_db->get_value_upper_bound (
990 NOTMUCH_VALUE_LAST_MOD);
991 if (last_mod.empty ())
992 notmuch->revision = 0;
994 notmuch->revision = Xapian::sortable_unserialise (last_mod);
995 notmuch->uuid = talloc_strdup (
996 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
998 notmuch->query_parser = new Xapian::QueryParser;
999 notmuch->term_gen = new Xapian::TermGenerator;
1000 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1001 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1002 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1003 #if HAVE_XAPIAN_FIELD_PROCESSOR
1004 /* This currently relies on the query parser to pass anything
1005 * with a .. to the range processor */
1006 notmuch->date_field_processor = new DateFieldProcessor();
1007 notmuch->query_parser->add_boolean_prefix("date", notmuch->date_field_processor);
1009 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1011 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1012 notmuch->query_parser->set_database (*notmuch->xapian_db);
1013 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1014 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1015 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1016 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1017 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1019 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
1020 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
1021 notmuch->query_parser->add_boolean_prefix (prefix->name,
1025 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
1026 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
1027 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
1029 } catch (const Xapian::Error &error) {
1030 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1031 error.get_msg().c_str()));
1032 notmuch_database_destroy (notmuch);
1034 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1038 talloc_free (local);
1042 *status_string = message;
1048 *database = notmuch;
1050 talloc_free (notmuch);
1055 notmuch_database_close (notmuch_database_t *notmuch)
1057 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1059 /* Many Xapian objects (and thus notmuch objects) hold references to
1060 * the database, so merely deleting the database may not suffice to
1061 * close it. Thus, we explicitly close it here. */
1062 if (notmuch->xapian_db != NULL) {
1064 /* If there's an outstanding transaction, it's unclear if
1065 * closing the Xapian database commits everything up to
1066 * that transaction, or may discard committed (but
1067 * unflushed) transactions. To be certain, explicitly
1068 * cancel any outstanding transaction before closing. */
1069 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1070 notmuch->atomic_nesting)
1071 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1072 ->cancel_transaction ();
1074 /* Close the database. This implicitly flushes
1075 * outstanding changes. */
1076 notmuch->xapian_db->close();
1077 } catch (const Xapian::Error &error) {
1078 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1079 if (! notmuch->exception_reported) {
1080 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1081 error.get_msg().c_str());
1086 delete notmuch->term_gen;
1087 notmuch->term_gen = NULL;
1088 delete notmuch->query_parser;
1089 notmuch->query_parser = NULL;
1090 delete notmuch->xapian_db;
1091 notmuch->xapian_db = NULL;
1092 delete notmuch->value_range_processor;
1093 notmuch->value_range_processor = NULL;
1094 delete notmuch->date_range_processor;
1095 notmuch->date_range_processor = NULL;
1096 delete notmuch->last_mod_range_processor;
1097 notmuch->last_mod_range_processor = NULL;
1102 #if HAVE_XAPIAN_COMPACT
1104 unlink_cb (const char *path,
1105 unused (const struct stat *sb),
1107 unused (struct FTW *ftw))
1109 return remove (path);
1113 rmtree (const char *path)
1115 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1118 class NotmuchCompactor : public Xapian::Compactor
1120 notmuch_compact_status_cb_t status_cb;
1121 void *status_closure;
1124 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1125 status_cb (cb), status_closure (closure) { }
1128 set_status (const std::string &table, const std::string &status)
1132 if (status_cb == NULL)
1135 if (status.length () == 0)
1136 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1138 msg = talloc_asprintf (NULL, " %s", status.c_str());
1144 status_cb (msg, status_closure);
1149 /* Compacts the given database, optionally saving the original database
1150 * in backup_path. Additionally, a callback function can be provided to
1151 * give the user feedback on the progress of the (likely long-lived)
1152 * compaction process.
1154 * The backup path must point to a directory on the same volume as the
1155 * original database. Passing a NULL backup_path will result in the
1156 * uncompacted database being deleted after compaction has finished.
1157 * Note that the database write lock will be held during the
1158 * compaction process to protect data integrity.
1161 notmuch_database_compact (const char *path,
1162 const char *backup_path,
1163 notmuch_compact_status_cb_t status_cb,
1167 char *notmuch_path, *xapian_path, *compact_xapian_path;
1168 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1169 notmuch_database_t *notmuch = NULL;
1170 struct stat statbuf;
1171 notmuch_bool_t keep_backup;
1172 char *message = NULL;
1174 local = talloc_new (NULL);
1176 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1178 ret = notmuch_database_open_verbose (path,
1179 NOTMUCH_DATABASE_MODE_READ_WRITE,
1183 if (status_cb) status_cb (message, closure);
1187 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1188 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1192 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1193 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1197 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1198 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1202 if (backup_path == NULL) {
1203 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1204 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1207 keep_backup = FALSE;
1213 if (stat (backup_path, &statbuf) != -1) {
1214 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1215 ret = NOTMUCH_STATUS_FILE_ERROR;
1218 if (errno != ENOENT) {
1219 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1221 ret = NOTMUCH_STATUS_FILE_ERROR;
1225 /* Unconditionally attempt to remove old work-in-progress database (if
1226 * any). This is "protected" by database lock. If this fails due to write
1227 * errors (etc), the following code will fail and provide error message.
1229 (void) rmtree (compact_xapian_path);
1232 NotmuchCompactor compactor (status_cb, closure);
1234 compactor.set_renumber (false);
1235 compactor.add_source (xapian_path);
1236 compactor.set_destdir (compact_xapian_path);
1237 compactor.compact ();
1238 } catch (const Xapian::Error &error) {
1239 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1240 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1244 if (rename (xapian_path, backup_path)) {
1245 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1246 xapian_path, backup_path, strerror (errno));
1247 ret = NOTMUCH_STATUS_FILE_ERROR;
1251 if (rename (compact_xapian_path, xapian_path)) {
1252 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1253 compact_xapian_path, xapian_path, strerror (errno));
1254 ret = NOTMUCH_STATUS_FILE_ERROR;
1258 if (! keep_backup) {
1259 if (rmtree (backup_path)) {
1260 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1261 backup_path, strerror (errno));
1262 ret = NOTMUCH_STATUS_FILE_ERROR;
1269 notmuch_status_t ret2;
1271 const char *str = notmuch_database_status_string (notmuch);
1272 if (status_cb && str)
1273 status_cb (str, closure);
1275 ret2 = notmuch_database_destroy (notmuch);
1277 /* don't clobber previous error status */
1278 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1282 talloc_free (local);
1288 notmuch_database_compact (unused (const char *path),
1289 unused (const char *backup_path),
1290 unused (notmuch_compact_status_cb_t status_cb),
1291 unused (void *closure))
1293 _notmuch_database_log (notmuch, "notmuch was compiled against a xapian version lacking compaction support.\n");
1294 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1299 notmuch_database_destroy (notmuch_database_t *notmuch)
1301 notmuch_status_t status;
1303 status = notmuch_database_close (notmuch);
1304 talloc_free (notmuch);
1310 notmuch_database_get_path (notmuch_database_t *notmuch)
1312 return notmuch->path;
1316 notmuch_database_get_version (notmuch_database_t *notmuch)
1318 unsigned int version;
1319 string version_string;
1323 version_string = notmuch->xapian_db->get_metadata ("version");
1324 if (version_string.empty ())
1327 str = version_string.c_str ();
1328 if (str == NULL || *str == '\0')
1331 version = strtoul (str, &end, 10);
1333 INTERNAL_ERROR ("Malformed database version: %s", str);
1339 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1341 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1342 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1343 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1346 static volatile sig_atomic_t do_progress_notify = 0;
1349 handle_sigalrm (unused (int signal))
1351 do_progress_notify = 1;
1354 /* Upgrade the current database.
1356 * After opening a database in read-write mode, the client should
1357 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1358 * if so, upgrade with this function before making any modifications.
1360 * The optional progress_notify callback can be used by the caller to
1361 * provide progress indication to the user. If non-NULL it will be
1362 * called periodically with 'count' as the number of messages upgraded
1363 * so far and 'total' the overall number of messages that will be
1367 notmuch_database_upgrade (notmuch_database_t *notmuch,
1368 void (*progress_notify) (void *closure,
1372 void *local = talloc_new (NULL);
1373 Xapian::TermIterator t, t_end;
1374 Xapian::WritableDatabase *db;
1375 struct sigaction action;
1376 struct itimerval timerval;
1377 notmuch_bool_t timer_is_active = FALSE;
1378 enum _notmuch_features target_features, new_features;
1379 notmuch_status_t status;
1380 notmuch_private_status_t private_status;
1381 notmuch_query_t *query = NULL;
1382 unsigned int count = 0, total = 0;
1384 status = _notmuch_database_ensure_writable (notmuch);
1388 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1390 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1391 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1393 if (! notmuch_database_needs_upgrade (notmuch))
1394 return NOTMUCH_STATUS_SUCCESS;
1396 if (progress_notify) {
1397 /* Set up our handler for SIGALRM */
1398 memset (&action, 0, sizeof (struct sigaction));
1399 action.sa_handler = handle_sigalrm;
1400 sigemptyset (&action.sa_mask);
1401 action.sa_flags = SA_RESTART;
1402 sigaction (SIGALRM, &action, NULL);
1404 /* Then start a timer to send SIGALRM once per second. */
1405 timerval.it_interval.tv_sec = 1;
1406 timerval.it_interval.tv_usec = 0;
1407 timerval.it_value.tv_sec = 1;
1408 timerval.it_value.tv_usec = 0;
1409 setitimer (ITIMER_REAL, &timerval, NULL);
1411 timer_is_active = TRUE;
1414 /* Figure out how much total work we need to do. */
1416 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1417 NOTMUCH_FEATURE_LAST_MOD)) {
1418 query = notmuch_query_create (notmuch, "");
1421 status = notmuch_query_count_messages_st (query, &msg_count);
1426 notmuch_query_destroy (query);
1429 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1430 t_end = db->allterms_end ("XTIMESTAMP");
1431 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1434 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1435 /* The ghost message upgrade converts all thread_id_*
1436 * metadata values into ghost message documents. */
1437 t_end = db->metadata_keys_end ("thread_id_");
1438 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1442 /* Perform the upgrade in a transaction. */
1443 db->begin_transaction (true);
1445 /* Set the target features so we write out changes in the desired
1447 notmuch->features = target_features;
1449 /* Perform per-message upgrades. */
1451 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1452 NOTMUCH_FEATURE_LAST_MOD)) {
1453 notmuch_messages_t *messages;
1454 notmuch_message_t *message;
1457 query = notmuch_query_create (notmuch, "");
1459 status = notmuch_query_search_messages_st (query, &messages);
1463 notmuch_messages_valid (messages);
1464 notmuch_messages_move_to_next (messages))
1466 if (do_progress_notify) {
1467 progress_notify (closure, (double) count / total);
1468 do_progress_notify = 0;
1471 message = notmuch_messages_get (messages);
1473 /* Before version 1, each message document had its
1474 * filename in the data field. Copy that into the new
1475 * format by calling notmuch_message_add_filename.
1477 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1478 filename = _notmuch_message_talloc_copy_data (message);
1479 if (filename && *filename != '\0') {
1480 _notmuch_message_add_filename (message, filename);
1481 _notmuch_message_clear_data (message);
1483 talloc_free (filename);
1486 /* Prior to version 2, the "folder:" prefix was
1487 * probabilistic and stemmed. Change it to the current
1488 * boolean prefix. Add "path:" prefixes while at it.
1490 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1491 _notmuch_message_upgrade_folder (message);
1493 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1494 * track modification revisions. Give all messages the
1495 * next available revision; since we just started tracking
1496 * revisions for this database, that will be 1.
1498 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1499 _notmuch_message_upgrade_last_mod (message);
1501 _notmuch_message_sync (message);
1503 notmuch_message_destroy (message);
1508 notmuch_query_destroy (query);
1512 /* Perform per-directory upgrades. */
1514 /* Before version 1 we stored directory timestamps in
1515 * XTIMESTAMP documents instead of the current XDIRECTORY
1516 * documents. So copy those as well. */
1517 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1518 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1520 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1524 Xapian::PostingIterator p, p_end;
1525 std::string term = *t;
1527 p_end = notmuch->xapian_db->postlist_end (term);
1529 for (p = notmuch->xapian_db->postlist_begin (term);
1533 Xapian::Document document;
1535 notmuch_directory_t *directory;
1537 if (do_progress_notify) {
1538 progress_notify (closure, (double) count / total);
1539 do_progress_notify = 0;
1542 document = find_document_for_doc_id (notmuch, *p);
1543 mtime = Xapian::sortable_unserialise (
1544 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1546 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1547 NOTMUCH_FIND_CREATE, &status);
1548 notmuch_directory_set_mtime (directory, mtime);
1549 notmuch_directory_destroy (directory);
1551 db->delete_document (*p);
1558 /* Perform metadata upgrades. */
1560 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1561 * messages were stored as database metadata. Change these to
1564 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1565 notmuch_message_t *message;
1566 std::string message_id, thread_id;
1568 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1569 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1571 if (do_progress_notify) {
1572 progress_notify (closure, (double) count / total);
1573 do_progress_notify = 0;
1576 message_id = (*t).substr (
1577 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1578 thread_id = db->get_metadata (*t);
1580 /* Create ghost message */
1581 message = _notmuch_message_create_for_message_id (
1582 notmuch, message_id.c_str (), &private_status);
1583 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1584 /* Document already exists; ignore the stored thread ID */
1585 } else if (private_status ==
1586 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1587 private_status = _notmuch_message_initialize_ghost (
1588 message, thread_id.c_str ());
1589 if (! private_status)
1590 _notmuch_message_sync (message);
1593 if (private_status) {
1594 _notmuch_database_log (notmuch,
1595 "Upgrade failed while creating ghost messages.\n");
1596 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1600 /* Clear saved metadata thread ID */
1601 db->set_metadata (*t, "");
1607 status = NOTMUCH_STATUS_SUCCESS;
1608 db->set_metadata ("features", _print_features (local, notmuch->features));
1609 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1612 if (status == NOTMUCH_STATUS_SUCCESS)
1613 db->commit_transaction ();
1615 db->cancel_transaction ();
1617 if (timer_is_active) {
1618 /* Now stop the timer. */
1619 timerval.it_interval.tv_sec = 0;
1620 timerval.it_interval.tv_usec = 0;
1621 timerval.it_value.tv_sec = 0;
1622 timerval.it_value.tv_usec = 0;
1623 setitimer (ITIMER_REAL, &timerval, NULL);
1625 /* And disable the signal handler. */
1626 action.sa_handler = SIG_IGN;
1627 sigaction (SIGALRM, &action, NULL);
1631 notmuch_query_destroy (query);
1633 talloc_free (local);
1638 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1640 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1641 notmuch->atomic_nesting > 0)
1644 if (notmuch_database_needs_upgrade(notmuch))
1645 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1648 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1649 } catch (const Xapian::Error &error) {
1650 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1651 error.get_msg().c_str());
1652 notmuch->exception_reported = TRUE;
1653 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1657 notmuch->atomic_nesting++;
1658 return NOTMUCH_STATUS_SUCCESS;
1662 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1664 Xapian::WritableDatabase *db;
1666 if (notmuch->atomic_nesting == 0)
1667 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1669 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1670 notmuch->atomic_nesting > 1)
1673 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1675 db->commit_transaction ();
1677 /* This is a hack for testing. Xapian never flushes on a
1678 * non-flushed commit, even if the flush threshold is 1.
1679 * However, we rely on flushing to test atomicity. */
1680 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1681 if (thresh && atoi (thresh) == 1)
1683 } catch (const Xapian::Error &error) {
1684 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1685 error.get_msg().c_str());
1686 notmuch->exception_reported = TRUE;
1687 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1690 if (notmuch->atomic_dirty) {
1691 ++notmuch->revision;
1692 notmuch->atomic_dirty = FALSE;
1696 notmuch->atomic_nesting--;
1697 return NOTMUCH_STATUS_SUCCESS;
1701 notmuch_database_get_revision (notmuch_database_t *notmuch,
1705 *uuid = notmuch->uuid;
1706 return notmuch->revision;
1709 /* We allow the user to use arbitrarily long paths for directories. But
1710 * we have a term-length limit. So if we exceed that, we'll use the
1711 * SHA-1 of the path for the database term.
1713 * Note: This function may return the original value of 'path'. If it
1714 * does not, then the caller is responsible to free() the returned
1718 _notmuch_database_get_directory_db_path (const char *path)
1720 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1722 if (term_len > NOTMUCH_TERM_MAX)
1723 return _notmuch_sha1_of_string (path);
1728 /* Given a path, split it into two parts: the directory part is all
1729 * components except for the last, and the basename is that last
1730 * component. Getting the return-value for either part is optional
1731 * (the caller can pass NULL).
1733 * The original 'path' can represent either a regular file or a
1734 * directory---the splitting will be carried out in the same way in
1735 * either case. Trailing slashes on 'path' will be ignored, and any
1736 * cases of multiple '/' characters appearing in series will be
1737 * treated as a single '/'.
1739 * Allocation (if any) will have 'ctx' as the talloc owner. But
1740 * pointers will be returned within the original path string whenever
1743 * Note: If 'path' is non-empty and contains no non-trailing slash,
1744 * (that is, consists of a filename with no parent directory), then
1745 * the directory returned will be an empty string. However, if 'path'
1746 * is an empty string, then both directory and basename will be
1750 _notmuch_database_split_path (void *ctx,
1752 const char **directory,
1753 const char **basename)
1757 if (path == NULL || *path == '\0') {
1762 return NOTMUCH_STATUS_SUCCESS;
1765 /* Find the last slash (not counting a trailing slash), if any. */
1767 slash = path + strlen (path) - 1;
1769 /* First, skip trailing slashes. */
1770 while (slash != path && *slash == '/')
1773 /* Then, find a slash. */
1774 while (slash != path && *slash != '/') {
1781 /* Finally, skip multiple slashes. */
1782 while (slash != path && *(slash - 1) == '/')
1785 if (slash == path) {
1787 *directory = talloc_strdup (ctx, "");
1792 *directory = talloc_strndup (ctx, path, slash - path);
1795 return NOTMUCH_STATUS_SUCCESS;
1798 /* Find the document ID of the specified directory.
1800 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1801 * created if one does not exist for 'path'. Otherwise, if the
1802 * directory document does not exist, this sets *directory_id to
1803 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1806 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1808 notmuch_find_flags_t flags,
1809 unsigned int *directory_id)
1811 notmuch_directory_t *directory;
1812 notmuch_status_t status;
1816 return NOTMUCH_STATUS_SUCCESS;
1819 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1820 if (status || !directory) {
1825 *directory_id = _notmuch_directory_get_document_id (directory);
1827 notmuch_directory_destroy (directory);
1829 return NOTMUCH_STATUS_SUCCESS;
1833 _notmuch_database_get_directory_path (void *ctx,
1834 notmuch_database_t *notmuch,
1835 unsigned int doc_id)
1837 Xapian::Document document;
1839 document = find_document_for_doc_id (notmuch, doc_id);
1841 return talloc_strdup (ctx, document.get_data ().c_str ());
1844 /* Given a legal 'filename' for the database, (either relative to
1845 * database path or absolute with initial components identical to
1846 * database path), return a new string (with 'ctx' as the talloc
1847 * owner) suitable for use as a direntry term value.
1849 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1850 * will be created in the database as needed. Otherwise, if the
1851 * necessary directory documents do not exist, this sets
1852 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1855 _notmuch_database_filename_to_direntry (void *ctx,
1856 notmuch_database_t *notmuch,
1857 const char *filename,
1858 notmuch_find_flags_t flags,
1861 const char *relative, *directory, *basename;
1862 Xapian::docid directory_id;
1863 notmuch_status_t status;
1865 relative = _notmuch_database_relative_path (notmuch, filename);
1867 status = _notmuch_database_split_path (ctx, relative,
1868 &directory, &basename);
1872 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1874 if (status || directory_id == (unsigned int)-1) {
1879 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1881 return NOTMUCH_STATUS_SUCCESS;
1884 /* Given a legal 'path' for the database, return the relative path.
1886 * The return value will be a pointer to the original path contents,
1887 * and will be either the original string (if 'path' was relative) or
1888 * a portion of the string (if path was absolute and begins with the
1892 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1895 const char *db_path, *relative;
1896 unsigned int db_path_len;
1898 db_path = notmuch_database_get_path (notmuch);
1899 db_path_len = strlen (db_path);
1903 if (*relative == '/') {
1904 while (*relative == '/' && *(relative+1) == '/')
1907 if (strncmp (relative, db_path, db_path_len) == 0)
1909 relative += db_path_len;
1910 while (*relative == '/')
1919 notmuch_database_get_directory (notmuch_database_t *notmuch,
1921 notmuch_directory_t **directory)
1923 notmuch_status_t status;
1925 if (directory == NULL)
1926 return NOTMUCH_STATUS_NULL_POINTER;
1930 *directory = _notmuch_directory_create (notmuch, path,
1931 NOTMUCH_FIND_LOOKUP, &status);
1932 } catch (const Xapian::Error &error) {
1933 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1934 error.get_msg().c_str());
1935 notmuch->exception_reported = TRUE;
1936 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1941 /* Allocate a document ID that satisfies the following criteria:
1943 * 1. The ID does not exist for any document in the Xapian database
1945 * 2. The ID was not previously returned from this function
1947 * 3. The ID is the smallest integer satisfying (1) and (2)
1949 * This function will trigger an internal error if these constraints
1950 * cannot all be satisfied, (that is, the pool of available document
1951 * IDs has been exhausted).
1954 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1956 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1958 notmuch->last_doc_id++;
1960 if (notmuch->last_doc_id == 0)
1961 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1963 return notmuch->last_doc_id;
1967 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1969 /* 16 bytes (+ terminator) for hexadecimal representation of
1970 * a 64-bit integer. */
1971 static char thread_id[17];
1972 Xapian::WritableDatabase *db;
1974 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1976 notmuch->last_thread_id++;
1978 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1980 db->set_metadata ("last_thread_id", thread_id);
1986 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1988 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1989 message_id = _notmuch_message_id_compressed (ctx, message_id);
1991 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1995 static notmuch_status_t
1996 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1998 const char *message_id,
1999 const char **thread_id_ret);
2001 /* Find the thread ID to which the message with 'message_id' belongs.
2003 * Note: 'thread_id_ret' must not be NULL!
2004 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2007 * Note: If there is no message in the database with the given
2008 * 'message_id' then a new thread_id will be allocated for this
2009 * message ID and stored in the database metadata so that the
2010 * thread ID can be looked up if the message is added to the database
2013 static notmuch_status_t
2014 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2016 const char *message_id,
2017 const char **thread_id_ret)
2019 notmuch_private_status_t status;
2020 notmuch_message_t *message;
2022 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2023 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2026 /* Look for this message (regular or ghost) */
2027 message = _notmuch_message_create_for_message_id (
2028 notmuch, message_id, &status);
2029 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2030 /* Message exists */
2031 *thread_id_ret = talloc_steal (
2032 ctx, notmuch_message_get_thread_id (message));
2033 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2034 /* Message did not exist. Give it a fresh thread ID and
2035 * populate this message as a ghost message. */
2036 *thread_id_ret = talloc_strdup (
2037 ctx, _notmuch_database_generate_thread_id (notmuch));
2038 if (! *thread_id_ret) {
2039 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2041 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2043 /* Commit the new ghost message */
2044 _notmuch_message_sync (message);
2047 /* Create failed. Fall through. */
2050 notmuch_message_destroy (message);
2052 return COERCE_STATUS (status, "Error creating ghost message");
2055 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2056 static notmuch_status_t
2057 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2059 const char *message_id,
2060 const char **thread_id_ret)
2062 notmuch_status_t status;
2063 notmuch_message_t *message;
2064 string thread_id_string;
2066 Xapian::WritableDatabase *db;
2068 status = notmuch_database_find_message (notmuch, message_id, &message);
2074 *thread_id_ret = talloc_steal (ctx,
2075 notmuch_message_get_thread_id (message));
2077 notmuch_message_destroy (message);
2079 return NOTMUCH_STATUS_SUCCESS;
2082 /* Message has not been seen yet.
2084 * We may have seen a reference to it already, in which case, we
2085 * can return the thread ID stored in the metadata. Otherwise, we
2086 * generate a new thread ID and store it there.
2088 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2089 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2090 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2092 if (thread_id_string.empty()) {
2093 *thread_id_ret = talloc_strdup (ctx,
2094 _notmuch_database_generate_thread_id (notmuch));
2095 db->set_metadata (metadata_key, *thread_id_ret);
2097 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2100 talloc_free (metadata_key);
2102 return NOTMUCH_STATUS_SUCCESS;
2105 static notmuch_status_t
2106 _merge_threads (notmuch_database_t *notmuch,
2107 const char *winner_thread_id,
2108 const char *loser_thread_id)
2110 Xapian::PostingIterator loser, loser_end;
2111 notmuch_message_t *message = NULL;
2112 notmuch_private_status_t private_status;
2113 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2115 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2117 for ( ; loser != loser_end; loser++) {
2118 message = _notmuch_message_create (notmuch, notmuch,
2119 *loser, &private_status);
2120 if (message == NULL) {
2121 ret = COERCE_STATUS (private_status,
2122 "Cannot find document for doc_id from query");
2126 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2127 _notmuch_message_add_term (message, "thread", winner_thread_id);
2128 _notmuch_message_sync (message);
2130 notmuch_message_destroy (message);
2136 notmuch_message_destroy (message);
2142 _my_talloc_free_for_g_hash (void *ptr)
2147 static notmuch_status_t
2148 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2149 notmuch_message_t *message,
2150 notmuch_message_file_t *message_file,
2151 const char **thread_id)
2153 GHashTable *parents = NULL;
2154 const char *refs, *in_reply_to, *in_reply_to_message_id;
2155 const char *last_ref_message_id, *this_message_id;
2156 GList *l, *keys = NULL;
2157 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2159 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2160 _my_talloc_free_for_g_hash, NULL);
2161 this_message_id = notmuch_message_get_message_id (message);
2163 refs = _notmuch_message_file_get_header (message_file, "references");
2164 last_ref_message_id = parse_references (message,
2168 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2169 in_reply_to_message_id = parse_references (message,
2171 parents, in_reply_to);
2173 /* For the parent of this message, use the last message ID of the
2174 * References header, if available. If not, fall back to the
2175 * first message ID in the In-Reply-To header. */
2176 if (last_ref_message_id) {
2177 _notmuch_message_add_term (message, "replyto",
2178 last_ref_message_id);
2179 } else if (in_reply_to_message_id) {
2180 _notmuch_message_add_term (message, "replyto",
2181 in_reply_to_message_id);
2184 keys = g_hash_table_get_keys (parents);
2185 for (l = keys; l; l = l->next) {
2186 char *parent_message_id;
2187 const char *parent_thread_id = NULL;
2189 parent_message_id = (char *) l->data;
2191 _notmuch_message_add_term (message, "reference",
2194 ret = _resolve_message_id_to_thread_id (notmuch,
2201 if (*thread_id == NULL) {
2202 *thread_id = talloc_strdup (message, parent_thread_id);
2203 _notmuch_message_add_term (message, "thread", *thread_id);
2204 } else if (strcmp (*thread_id, parent_thread_id)) {
2205 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2215 g_hash_table_unref (parents);
2220 static notmuch_status_t
2221 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2222 notmuch_message_t *message,
2223 const char **thread_id)
2225 const char *message_id = notmuch_message_get_message_id (message);
2226 Xapian::PostingIterator child, children_end;
2227 notmuch_message_t *child_message = NULL;
2228 const char *child_thread_id;
2229 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2230 notmuch_private_status_t private_status;
2232 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2234 for ( ; child != children_end; child++) {
2236 child_message = _notmuch_message_create (message, notmuch,
2237 *child, &private_status);
2238 if (child_message == NULL) {
2239 ret = COERCE_STATUS (private_status,
2240 "Cannot find document for doc_id from query");
2244 child_thread_id = notmuch_message_get_thread_id (child_message);
2245 if (*thread_id == NULL) {
2246 *thread_id = talloc_strdup (message, child_thread_id);
2247 _notmuch_message_add_term (message, "thread", *thread_id);
2248 } else if (strcmp (*thread_id, child_thread_id)) {
2249 _notmuch_message_remove_term (child_message, "reference",
2251 _notmuch_message_sync (child_message);
2252 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2257 notmuch_message_destroy (child_message);
2258 child_message = NULL;
2263 notmuch_message_destroy (child_message);
2268 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2270 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2271 notmuch_message_t *message)
2273 const char *message_id;
2277 message_id = notmuch_message_get_message_id (message);
2278 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2280 /* Check if we have already seen related messages to this one.
2281 * If we have then use the thread_id that we stored at that time.
2283 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2284 if (stored_id.empty ()) {
2287 Xapian::WritableDatabase *db;
2289 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2291 /* Clear the metadata for this message ID. We don't need it
2293 db->set_metadata (metadata_key, "");
2295 return talloc_strdup (ctx, stored_id.c_str ());
2299 /* Given a blank or ghost 'message' and its corresponding
2300 * 'message_file' link it to existing threads in the database.
2302 * First, if is_ghost, this retrieves the thread ID already stored in
2303 * the message (which will be the case if a message was previously
2304 * added that referenced this one). If the message is blank
2305 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2306 * later in this function). If the database does not support ghost
2307 * messages, this checks for a thread ID stored in database metadata
2308 * for this message ID.
2310 * Second, we look at 'message_file' and its link-relevant headers
2311 * (References and In-Reply-To) for message IDs.
2313 * Finally, we look in the database for existing message that
2314 * reference 'message'.
2316 * In all cases, we assign to the current message the first thread ID
2317 * found. We will also merge any existing, distinct threads where this
2318 * message belongs to both, (which is not uncommon when messages are
2319 * processed out of order).
2321 * Finally, if no thread ID has been found through referenced messages, we
2322 * call _notmuch_message_generate_thread_id to generate a new thread
2323 * ID. This should only happen for new, top-level messages, (no
2324 * References or In-Reply-To header in this message, and no previously
2325 * added message refers to this message).
2327 static notmuch_status_t
2328 _notmuch_database_link_message (notmuch_database_t *notmuch,
2329 notmuch_message_t *message,
2330 notmuch_message_file_t *message_file,
2331 notmuch_bool_t is_ghost)
2333 void *local = talloc_new (NULL);
2334 notmuch_status_t status;
2335 const char *thread_id = NULL;
2337 /* Check if the message already had a thread ID */
2338 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2340 thread_id = notmuch_message_get_thread_id (message);
2342 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2344 _notmuch_message_add_term (message, "thread", thread_id);
2347 status = _notmuch_database_link_message_to_parents (notmuch, message,
2353 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2354 /* In general, it shouldn't be necessary to link children,
2355 * since the earlier indexing of those children will have
2356 * stored a thread ID for the missing parent. However, prior
2357 * to ghost messages, these stored thread IDs were NOT
2358 * rewritten during thread merging (and there was no
2359 * performant way to do so), so if indexed children were
2360 * pulled into a different thread ID by a merge, it was
2361 * necessary to pull them *back* into the stored thread ID of
2362 * the parent. With ghost messages, we just rewrite the
2363 * stored thread IDs during merging, so this workaround isn't
2365 status = _notmuch_database_link_message_to_children (notmuch, message,
2371 /* If not part of any existing thread, generate a new thread ID. */
2372 if (thread_id == NULL) {
2373 thread_id = _notmuch_database_generate_thread_id (notmuch);
2375 _notmuch_message_add_term (message, "thread", thread_id);
2379 talloc_free (local);
2385 notmuch_database_add_message (notmuch_database_t *notmuch,
2386 const char *filename,
2387 notmuch_message_t **message_ret)
2389 notmuch_message_file_t *message_file;
2390 notmuch_message_t *message = NULL;
2391 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2392 notmuch_private_status_t private_status;
2393 notmuch_bool_t is_ghost = false;
2395 const char *date, *header;
2396 const char *from, *to, *subject;
2397 char *message_id = NULL;
2400 *message_ret = NULL;
2402 ret = _notmuch_database_ensure_writable (notmuch);
2406 message_file = _notmuch_message_file_open (notmuch, filename);
2407 if (message_file == NULL)
2408 return NOTMUCH_STATUS_FILE_ERROR;
2410 /* Adding a message may change many documents. Do this all
2412 ret = notmuch_database_begin_atomic (notmuch);
2416 /* Parse message up front to get better error status. */
2417 ret = _notmuch_message_file_parse (message_file);
2422 /* Before we do any real work, (especially before doing a
2423 * potential SHA-1 computation on the entire file's contents),
2424 * let's make sure that what we're looking at looks like an
2425 * actual email message.
2427 from = _notmuch_message_file_get_header (message_file, "from");
2428 subject = _notmuch_message_file_get_header (message_file, "subject");
2429 to = _notmuch_message_file_get_header (message_file, "to");
2431 if ((from == NULL || *from == '\0') &&
2432 (subject == NULL || *subject == '\0') &&
2433 (to == NULL || *to == '\0'))
2435 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2439 /* Now that we're sure it's mail, the first order of business
2440 * is to find a message ID (or else create one ourselves). */
2442 header = _notmuch_message_file_get_header (message_file, "message-id");
2443 if (header && *header != '\0') {
2444 message_id = _parse_message_id (message_file, header, NULL);
2446 /* So the header value isn't RFC-compliant, but it's
2447 * better than no message-id at all. */
2448 if (message_id == NULL)
2449 message_id = talloc_strdup (message_file, header);
2452 if (message_id == NULL ) {
2453 /* No message-id at all, let's generate one by taking a
2454 * hash over the file's contents. */
2455 char *sha1 = _notmuch_sha1_of_file (filename);
2457 /* If that failed too, something is really wrong. Give up. */
2459 ret = NOTMUCH_STATUS_FILE_ERROR;
2463 message_id = talloc_asprintf (message_file,
2464 "notmuch-sha1-%s", sha1);
2468 /* Now that we have a message ID, we get a message object,
2469 * (which may or may not reference an existing document in the
2472 message = _notmuch_message_create_for_message_id (notmuch,
2476 talloc_free (message_id);
2478 if (message == NULL) {
2479 ret = COERCE_STATUS (private_status,
2480 "Unexpected status value from _notmuch_message_create_for_message_id");
2484 _notmuch_message_add_filename (message, filename);
2486 /* Is this a newly created message object or a ghost
2487 * message? We have to be slightly careful: if this is a
2488 * blank message, it's not safe to call
2489 * notmuch_message_get_flag yet. */
2490 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2491 (is_ghost = notmuch_message_get_flag (
2492 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2493 _notmuch_message_add_term (message, "type", "mail");
2495 /* Convert ghost message to a regular message */
2496 _notmuch_message_remove_term (message, "type", "ghost");
2498 ret = _notmuch_database_link_message (notmuch, message,
2499 message_file, is_ghost);
2503 date = _notmuch_message_file_get_header (message_file, "date");
2504 _notmuch_message_set_header_values (message, date, from, subject);
2506 ret = _notmuch_message_index_file (message, message_file);
2510 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2513 _notmuch_message_sync (message);
2514 } catch (const Xapian::Error &error) {
2515 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2516 error.get_msg().c_str());
2517 notmuch->exception_reported = TRUE;
2518 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2524 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2525 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2526 *message_ret = message;
2528 notmuch_message_destroy (message);
2532 _notmuch_message_file_close (message_file);
2534 ret2 = notmuch_database_end_atomic (notmuch);
2535 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2536 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2537 ret2 != NOTMUCH_STATUS_SUCCESS)
2544 notmuch_database_remove_message (notmuch_database_t *notmuch,
2545 const char *filename)
2547 notmuch_status_t status;
2548 notmuch_message_t *message;
2550 status = notmuch_database_find_message_by_filename (notmuch, filename,
2553 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2554 status = _notmuch_message_remove_filename (message, filename);
2555 if (status == NOTMUCH_STATUS_SUCCESS)
2556 _notmuch_message_delete (message);
2557 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2558 _notmuch_message_sync (message);
2560 notmuch_message_destroy (message);
2567 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2568 const char *filename,
2569 notmuch_message_t **message_ret)
2572 const char *prefix = _find_prefix ("file-direntry");
2573 char *direntry, *term;
2574 Xapian::PostingIterator i, end;
2575 notmuch_status_t status;
2577 if (message_ret == NULL)
2578 return NOTMUCH_STATUS_NULL_POINTER;
2580 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2581 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2583 /* return NULL on any failure */
2584 *message_ret = NULL;
2586 local = talloc_new (notmuch);
2589 status = _notmuch_database_filename_to_direntry (
2590 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2591 if (status || !direntry)
2594 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2596 find_doc_ids_for_term (notmuch, term, &i, &end);
2599 notmuch_private_status_t private_status;
2601 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2603 if (*message_ret == NULL)
2604 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2606 } catch (const Xapian::Error &error) {
2607 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2608 error.get_msg().c_str());
2609 notmuch->exception_reported = TRUE;
2610 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2614 talloc_free (local);
2616 if (status && *message_ret) {
2617 notmuch_message_destroy (*message_ret);
2618 *message_ret = NULL;
2623 notmuch_string_list_t *
2624 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2625 Xapian::TermIterator &end,
2628 int prefix_len = strlen (prefix);
2629 notmuch_string_list_t *list;
2631 list = _notmuch_string_list_create (ctx);
2632 if (unlikely (list == NULL))
2635 for (i.skip_to (prefix); i != end; i++) {
2636 /* Terminate loop at first term without desired prefix. */
2637 if (strncmp ((*i).c_str (), prefix, prefix_len))
2640 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2647 notmuch_database_get_all_tags (notmuch_database_t *db)
2649 Xapian::TermIterator i, end;
2650 notmuch_string_list_t *tags;
2653 i = db->xapian_db->allterms_begin();
2654 end = db->xapian_db->allterms_end();
2655 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2656 _find_prefix ("tag"));
2657 _notmuch_string_list_sort (tags);
2658 return _notmuch_tags_create (db, tags);
2659 } catch (const Xapian::Error &error) {
2660 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2661 error.get_msg().c_str());
2662 db->exception_reported = TRUE;
2668 notmuch_database_status_string (const notmuch_database_t *notmuch)
2670 return notmuch->status_string;