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 * In addition, terms from the content of the message are added with
105 * "from", "to", "attachment", and "subject" prefixes for use by the
106 * user in searching. Similarly, terms from the path of the mail
107 * message are added with "folder" and "path" prefixes. But the
108 * database doesn't really care itself about any of these.
110 * The data portion of a mail document is empty.
112 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
113 * -----------------------------------------------
114 * A ghost mail document is like a mail document, but where we don't
115 * have the message content. These are used to track thread reference
116 * information for messages we haven't received.
118 * A ghost mail document has type: ghost; id and thread fields that
119 * are identical to the mail document fields; and a MESSAGE_ID value.
123 * A directory document is used by a client of the notmuch library to
124 * maintain data necessary to allow for efficient polling of mail
127 * All directory documents contain one term:
129 * directory: The directory path (relative to the database path)
130 * Or the SHA1 sum of the directory path (if the
131 * path itself is too long to fit in a Xapian
134 * And all directory documents for directories other than top-level
135 * directories also contain the following term:
137 * directory-direntry: A colon-separated pair of values
138 * (INTEGER:STRING), where INTEGER is the
139 * document ID of the parent directory
140 * document, and STRING is the name of this
141 * directory within that parent.
143 * All directory documents have a single value:
145 * TIMESTAMP: The mtime of the directory (at last scan)
147 * The data portion of a directory document contains the path of the
148 * directory (relative to the database path).
152 * Xapian allows us to store arbitrary name-value pairs as
153 * "metadata". We currently use the following metadata names with the
156 * version The database schema version, (which is distinct
157 * from both the notmuch package version (see
158 * notmuch --version) and the libnotmuch library
159 * version. The version is stored as an base-10
160 * ASCII integer. The initial database version
161 * was 1, (though a schema existed before that
162 * were no "version" database value existed at
163 * all). Successive versions are allocated as
164 * changes are made to the database (such as by
165 * indexing new fields).
167 * features The set of features supported by this
168 * database. This consists of a set of
169 * '\n'-separated lines, where each is a feature
170 * name, a '\t', and compatibility flags. If the
171 * compatibility flags contain 'w', then the
172 * opener must support this feature to safely
173 * write this database. If the compatibility
174 * flags contain 'r', then the opener must
175 * support this feature to read this database.
176 * Introduced in database version 3.
178 * last_thread_id The last thread ID generated. This is stored
179 * as a 16-byte hexadecimal ASCII representation
180 * of a 64-bit unsigned integer. The first ID
181 * generated is 1 and the value will be
182 * incremented for each thread ID.
187 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
188 * Instead, the database has the following additional database
191 * thread_id_* A pre-allocated thread ID for a particular
192 * message. This is actually an arbitrarily large
193 * family of metadata name. Any particular name is
194 * formed by concatenating "thread_id_" with a message
195 * ID (or the SHA1 sum of a message ID if it is very
196 * long---see description of 'id' in the mail
197 * document). The value stored is a thread ID.
199 * These thread ID metadata values are stored
200 * whenever a message references a parent message
201 * that does not yet exist in the database. A
202 * thread ID will be allocated and stored, and if
203 * the message is later added, the stored thread
204 * ID will be used (and the metadata value will
207 * Even before a message is added, it's
208 * pre-allocated thread ID is useful so that all
209 * descendant messages that reference this common
210 * parent can be recognized as belonging to the
214 /* With these prefix values we follow the conventions published here:
216 * http://xapian.org/docs/omega/termprefixes.html
218 * as much as makes sense. Note that I took some liberty in matching
219 * the reserved prefix values to notmuch concepts, (for example, 'G'
220 * is documented as "newsGroup (or similar entity - e.g. a web forum
221 * name)", for which I think the thread is the closest analogue in
222 * notmuch. This in spite of the fact that we will eventually be
223 * storing mailing-list messages where 'G' for "mailing list name"
224 * might be even a closer analogue. I'm treating the single-character
225 * prefixes preferentially for core notmuch concepts (which will be
226 * nearly universal to all mail messages).
229 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
231 { "reference", "XREFERENCE" },
232 { "replyto", "XREPLYTO" },
233 { "directory", "XDIRECTORY" },
234 { "file-direntry", "XFDIRENTRY" },
235 { "directory-direntry", "XDDIRENTRY" },
238 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
245 * Without the ":", since this is a multi-letter prefix, Xapian
246 * will add a colon itself if the first letter of the path is
247 * upper-case ASCII. Including the ":" forces there to always be a
248 * colon, which keeps our own logic simpler.
250 { "folder", "XFOLDER:" },
253 static prefix_t PROBABILISTIC_PREFIX[]= {
256 { "attachment", "XATTACHMENT" },
257 { "mimetype", "XMIMETYPE"},
258 { "subject", "XSUBJECT"},
262 _find_prefix (const char *name)
266 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
267 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
268 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
271 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
272 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
273 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
276 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
277 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
278 return PROBABILISTIC_PREFIX[i].prefix;
281 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
286 static const struct {
287 /* NOTMUCH_FEATURE_* value. */
288 _notmuch_features value;
289 /* Feature name as it appears in the database. This name should
290 * be appropriate for displaying to the user if an older version
291 * of notmuch doesn't support this feature. */
293 /* Compatibility flags when this feature is declared. */
295 } feature_names[] = {
296 { NOTMUCH_FEATURE_FILE_TERMS,
297 "multiple paths per message", "rw" },
298 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
299 "relative directory paths", "rw" },
300 /* Header values are not required for reading a database because a
301 * reader can just refer to the message file. */
302 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
303 "from/subject/message-ID in database", "w" },
304 { NOTMUCH_FEATURE_BOOL_FOLDER,
305 "exact folder:/path: search", "rw" },
306 { NOTMUCH_FEATURE_GHOSTS,
307 "mail documents for missing messages", "w"},
308 /* Knowledge of the index mime-types are not required for reading
309 * a database because a reader will just be unable to query
311 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
312 "indexed MIME types", "w"},
316 notmuch_status_to_string (notmuch_status_t status)
319 case NOTMUCH_STATUS_SUCCESS:
320 return "No error occurred";
321 case NOTMUCH_STATUS_OUT_OF_MEMORY:
322 return "Out of memory";
323 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
324 return "Attempt to write to a read-only database";
325 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
326 return "A Xapian exception occurred";
327 case NOTMUCH_STATUS_FILE_ERROR:
328 return "Something went wrong trying to read or write a file";
329 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
330 return "File is not an email";
331 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
332 return "Message ID is identical to a message in database";
333 case NOTMUCH_STATUS_NULL_POINTER:
334 return "Erroneous NULL pointer";
335 case NOTMUCH_STATUS_TAG_TOO_LONG:
336 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
337 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
338 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
339 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
340 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
341 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
342 return "Unsupported operation";
343 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
344 return "Operation requires a database upgrade";
345 case NOTMUCH_STATUS_PATH_ERROR:
346 return "Path supplied is illegal for this function";
348 case NOTMUCH_STATUS_LAST_STATUS:
349 return "Unknown error status value";
354 _notmuch_database_log (notmuch_database_t *notmuch,
360 va_start (va_args, format);
362 if (notmuch->status_string)
363 talloc_free (notmuch->status_string);
365 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
371 find_doc_ids_for_term (notmuch_database_t *notmuch,
373 Xapian::PostingIterator *begin,
374 Xapian::PostingIterator *end)
376 *begin = notmuch->xapian_db->postlist_begin (term);
378 *end = notmuch->xapian_db->postlist_end (term);
382 find_doc_ids (notmuch_database_t *notmuch,
383 const char *prefix_name,
385 Xapian::PostingIterator *begin,
386 Xapian::PostingIterator *end)
390 term = talloc_asprintf (notmuch, "%s%s",
391 _find_prefix (prefix_name), value);
393 find_doc_ids_for_term (notmuch, term, begin, end);
398 notmuch_private_status_t
399 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
400 const char *prefix_name,
402 unsigned int *doc_id)
404 Xapian::PostingIterator i, end;
406 find_doc_ids (notmuch, prefix_name, value, &i, &end);
410 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
415 #if DEBUG_DATABASE_SANITY
419 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
423 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
426 static Xapian::Document
427 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
429 return notmuch->xapian_db->get_document (doc_id);
432 /* Generate a compressed version of 'message_id' of the form:
434 * notmuch-sha1-<sha1_sum_of_message_id>
437 _notmuch_message_id_compressed (void *ctx, const char *message_id)
439 char *sha1, *compressed;
441 sha1 = _notmuch_sha1_of_string (message_id);
443 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
450 notmuch_database_find_message (notmuch_database_t *notmuch,
451 const char *message_id,
452 notmuch_message_t **message_ret)
454 notmuch_private_status_t status;
457 if (message_ret == NULL)
458 return NOTMUCH_STATUS_NULL_POINTER;
460 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
461 message_id = _notmuch_message_id_compressed (notmuch, message_id);
464 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
465 message_id, &doc_id);
467 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
470 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
472 if (*message_ret == NULL)
473 return NOTMUCH_STATUS_OUT_OF_MEMORY;
476 return NOTMUCH_STATUS_SUCCESS;
477 } catch (const Xapian::Error &error) {
478 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
479 error.get_msg().c_str());
480 notmuch->exception_reported = TRUE;
482 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
486 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
487 * a (potentially nested) parenthesized sequence with '\' used to
488 * escape any character (including parentheses).
490 * If the sequence to be skipped continues to the end of the string,
491 * then 'str' will be left pointing at the final terminating '\0'
495 skip_space_and_comments (const char **str)
500 while (*s && (isspace (*s) || *s == '(')) {
501 while (*s && isspace (*s))
506 while (*s && nesting) {
509 } else if (*s == ')') {
511 } else if (*s == '\\') {
523 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
524 * comments, and the '<' and '>' delimiters.
526 * If not NULL, then *next will be made to point to the first character
527 * not parsed, (possibly pointing to the final '\0' terminator.
529 * Returns a newly talloc'ed string belonging to 'ctx'.
531 * Returns NULL if there is any error parsing the message-id. */
533 _parse_message_id (void *ctx, const char *message_id, const char **next)
538 if (message_id == NULL || *message_id == '\0')
543 skip_space_and_comments (&s);
545 /* Skip any unstructured text as well. */
546 while (*s && *s != '<')
557 skip_space_and_comments (&s);
560 while (*end && *end != '>')
569 if (end > s && *end == '>')
574 result = talloc_strndup (ctx, s, end - s + 1);
576 /* Finally, collapse any whitespace that is within the message-id
582 for (r = result, len = strlen (r); *r; r++, len--)
583 if (*r == ' ' || *r == '\t')
584 memmove (r, r+1, len);
590 /* Parse a References header value, putting a (talloc'ed under 'ctx')
591 * copy of each referenced message-id into 'hash'.
593 * We explicitly avoid including any reference identical to
594 * 'message_id' in the result (to avoid mass confusion when a single
595 * message references itself cyclically---and yes, mail messages are
596 * not infrequent in the wild that do this---don't ask me why).
598 * Return the last reference parsed, if it is not equal to message_id.
601 parse_references (void *ctx,
602 const char *message_id,
606 char *ref, *last_ref = NULL;
608 if (refs == NULL || *refs == '\0')
612 ref = _parse_message_id (ctx, refs, &refs);
614 if (ref && strcmp (ref, message_id)) {
615 g_hash_table_insert (hash, ref, NULL);
620 /* The return value of this function is used to add a parent
621 * reference to the database. We should avoid making a message
622 * its own parent, thus the above check.
628 notmuch_database_create (const char *path, notmuch_database_t **database)
630 char *status_string = NULL;
631 notmuch_status_t status;
633 status = notmuch_database_create_verbose (path, database,
637 fputs (status_string, stderr);
638 free (status_string);
645 notmuch_database_create_verbose (const char *path,
646 notmuch_database_t **database,
647 char **status_string)
649 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
650 notmuch_database_t *notmuch = NULL;
651 char *notmuch_path = NULL;
652 char *message = NULL;
657 message = strdup ("Error: Cannot create a database for a NULL path.\n");
658 status = NOTMUCH_STATUS_NULL_POINTER;
662 err = stat (path, &st);
664 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
665 path, strerror (errno)));
666 status = NOTMUCH_STATUS_FILE_ERROR;
670 if (! S_ISDIR (st.st_mode)) {
671 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
672 "Not a directory.\n",
674 status = NOTMUCH_STATUS_FILE_ERROR;
678 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
680 err = mkdir (notmuch_path, 0755);
683 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
684 notmuch_path, strerror (errno)));
685 status = NOTMUCH_STATUS_FILE_ERROR;
689 status = notmuch_database_open_verbose (path,
690 NOTMUCH_DATABASE_MODE_READ_WRITE,
695 /* Upgrade doesn't add these feature to existing databases, but
696 * new databases have them. */
697 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
698 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
700 status = notmuch_database_upgrade (notmuch, NULL, NULL);
702 notmuch_database_close(notmuch);
708 talloc_free (notmuch_path);
712 *status_string = message;
719 talloc_free (notmuch);
724 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
726 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
727 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
728 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
731 return NOTMUCH_STATUS_SUCCESS;
734 /* Parse a database features string from the given database version.
735 * Returns the feature bit set.
737 * For version < 3, this ignores the features string and returns a
738 * hard-coded set of features.
740 * If there are unrecognized features that are required to open the
741 * database in mode (which should be 'r' or 'w'), return a
742 * comma-separated list of unrecognized but required features in
743 * *incompat_out suitable for presenting to the user. *incompat_out
744 * will be allocated from ctx.
746 static _notmuch_features
747 _parse_features (const void *ctx, const char *features, unsigned int version,
748 char mode, char **incompat_out)
750 _notmuch_features res = static_cast<_notmuch_features>(0);
751 unsigned int namelen, i;
755 /* Prior to database version 3, features were implied by the
758 return NOTMUCH_FEATURES_V0;
759 else if (version == 1)
760 return NOTMUCH_FEATURES_V1;
761 else if (version == 2)
762 return NOTMUCH_FEATURES_V2;
764 /* Parse the features string */
765 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
766 flags = strchr (features, '\t');
767 if (! flags || flags > features + llen)
769 namelen = flags - features;
771 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
772 if (strlen (feature_names[i].name) == namelen &&
773 strncmp (feature_names[i].name, features, namelen) == 0) {
774 res |= feature_names[i].value;
779 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
780 /* Unrecognized feature */
781 const char *have = strchr (flags, mode);
782 if (have && have < features + llen) {
783 /* This feature is required to access this database in
784 * 'mode', but we don't understand it. */
786 *incompat_out = talloc_strdup (ctx, "");
787 *incompat_out = talloc_asprintf_append_buffer (
788 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
798 _print_features (const void *ctx, unsigned int features)
801 char *res = talloc_strdup (ctx, "");
803 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
804 if (features & feature_names[i].value)
805 res = talloc_asprintf_append_buffer (
806 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
812 notmuch_database_open (const char *path,
813 notmuch_database_mode_t mode,
814 notmuch_database_t **database)
816 char *status_string = NULL;
817 notmuch_status_t status;
819 status = notmuch_database_open_verbose (path, mode, database,
823 fputs (status_string, stderr);
824 free (status_string);
831 notmuch_database_open_verbose (const char *path,
832 notmuch_database_mode_t mode,
833 notmuch_database_t **database,
834 char **status_string)
836 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
837 void *local = talloc_new (NULL);
838 notmuch_database_t *notmuch = NULL;
839 char *notmuch_path, *xapian_path, *incompat_features;
840 char *message = NULL;
843 unsigned int i, version;
844 static int initialized = 0;
847 message = strdup ("Error: Cannot open a database for a NULL path.\n");
848 status = NOTMUCH_STATUS_NULL_POINTER;
852 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
853 message = strdup ("Out of memory\n");
854 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
858 err = stat (notmuch_path, &st);
860 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
861 notmuch_path, strerror (errno)));
862 status = NOTMUCH_STATUS_FILE_ERROR;
866 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
867 message = strdup ("Out of memory\n");
868 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
872 /* Initialize the GLib type system and threads */
873 #if !GLIB_CHECK_VERSION(2, 35, 1)
877 /* Initialize gmime */
879 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
883 notmuch = talloc_zero (NULL, notmuch_database_t);
884 notmuch->exception_reported = FALSE;
885 notmuch->status_string = NULL;
886 notmuch->path = talloc_strdup (notmuch, path);
888 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
889 notmuch->path[strlen (notmuch->path) - 1] = '\0';
891 notmuch->mode = mode;
892 notmuch->atomic_nesting = 0;
894 string last_thread_id;
896 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
897 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
898 Xapian::DB_CREATE_OR_OPEN);
900 notmuch->xapian_db = new Xapian::Database (xapian_path);
903 /* Check version. As of database version 3, we represent
904 * changes in terms of features, so assume a version bump
905 * means a dramatically incompatible change. */
906 version = notmuch_database_get_version (notmuch);
907 if (version > NOTMUCH_DATABASE_VERSION) {
908 IGNORE_RESULT (asprintf (&message,
909 "Error: Notmuch database at %s\n"
910 " has a newer database format version (%u) than supported by this\n"
911 " version of notmuch (%u).\n",
912 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
913 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
914 notmuch_database_destroy (notmuch);
916 status = NOTMUCH_STATUS_FILE_ERROR;
920 /* Check features. */
921 incompat_features = NULL;
922 notmuch->features = _parse_features (
923 local, notmuch->xapian_db->get_metadata ("features").c_str (),
924 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
926 if (incompat_features) {
927 IGNORE_RESULT (asprintf (&message,
928 "Error: Notmuch database at %s\n"
929 " requires features (%s)\n"
930 " not supported by this version of notmuch.\n",
931 notmuch_path, incompat_features));
932 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
933 notmuch_database_destroy (notmuch);
935 status = NOTMUCH_STATUS_FILE_ERROR;
939 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
940 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
941 if (last_thread_id.empty ()) {
942 notmuch->last_thread_id = 0;
947 str = last_thread_id.c_str ();
948 notmuch->last_thread_id = strtoull (str, &end, 16);
950 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
953 notmuch->query_parser = new Xapian::QueryParser;
954 notmuch->term_gen = new Xapian::TermGenerator;
955 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
956 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
957 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
959 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
960 notmuch->query_parser->set_database (*notmuch->xapian_db);
961 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
962 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
963 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
964 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
966 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
967 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
968 notmuch->query_parser->add_boolean_prefix (prefix->name,
972 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
973 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
974 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
976 } catch (const Xapian::Error &error) {
977 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
978 error.get_msg().c_str()));
979 notmuch_database_destroy (notmuch);
981 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
989 *status_string = message;
997 talloc_free (notmuch);
1002 notmuch_database_close (notmuch_database_t *notmuch)
1004 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1006 /* Many Xapian objects (and thus notmuch objects) hold references to
1007 * the database, so merely deleting the database may not suffice to
1008 * close it. Thus, we explicitly close it here. */
1009 if (notmuch->xapian_db != NULL) {
1011 /* If there's an outstanding transaction, it's unclear if
1012 * closing the Xapian database commits everything up to
1013 * that transaction, or may discard committed (but
1014 * unflushed) transactions. To be certain, explicitly
1015 * cancel any outstanding transaction before closing. */
1016 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1017 notmuch->atomic_nesting)
1018 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1019 ->cancel_transaction ();
1021 /* Close the database. This implicitly flushes
1022 * outstanding changes. */
1023 notmuch->xapian_db->close();
1024 } catch (const Xapian::Error &error) {
1025 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1026 if (! notmuch->exception_reported) {
1027 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1028 error.get_msg().c_str());
1033 delete notmuch->term_gen;
1034 notmuch->term_gen = NULL;
1035 delete notmuch->query_parser;
1036 notmuch->query_parser = NULL;
1037 delete notmuch->xapian_db;
1038 notmuch->xapian_db = NULL;
1039 delete notmuch->value_range_processor;
1040 notmuch->value_range_processor = NULL;
1041 delete notmuch->date_range_processor;
1042 notmuch->date_range_processor = NULL;
1047 #if HAVE_XAPIAN_COMPACT
1049 unlink_cb (const char *path,
1050 unused (const struct stat *sb),
1052 unused (struct FTW *ftw))
1054 return remove (path);
1058 rmtree (const char *path)
1060 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1063 class NotmuchCompactor : public Xapian::Compactor
1065 notmuch_compact_status_cb_t status_cb;
1066 void *status_closure;
1069 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1070 status_cb (cb), status_closure (closure) { }
1073 set_status (const std::string &table, const std::string &status)
1077 if (status_cb == NULL)
1080 if (status.length () == 0)
1081 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1083 msg = talloc_asprintf (NULL, " %s", status.c_str());
1089 status_cb (msg, status_closure);
1094 /* Compacts the given database, optionally saving the original database
1095 * in backup_path. Additionally, a callback function can be provided to
1096 * give the user feedback on the progress of the (likely long-lived)
1097 * compaction process.
1099 * The backup path must point to a directory on the same volume as the
1100 * original database. Passing a NULL backup_path will result in the
1101 * uncompacted database being deleted after compaction has finished.
1102 * Note that the database write lock will be held during the
1103 * compaction process to protect data integrity.
1106 notmuch_database_compact (const char *path,
1107 const char *backup_path,
1108 notmuch_compact_status_cb_t status_cb,
1112 char *notmuch_path, *xapian_path, *compact_xapian_path;
1113 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1114 notmuch_database_t *notmuch = NULL;
1115 struct stat statbuf;
1116 notmuch_bool_t keep_backup;
1117 char *message = NULL;
1119 local = talloc_new (NULL);
1121 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1123 ret = notmuch_database_open_verbose (path,
1124 NOTMUCH_DATABASE_MODE_READ_WRITE,
1128 if (status_cb) status_cb (message, closure);
1132 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1133 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1137 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1138 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1142 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1143 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1147 if (backup_path == NULL) {
1148 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1149 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1152 keep_backup = FALSE;
1158 if (stat (backup_path, &statbuf) != -1) {
1159 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1160 ret = NOTMUCH_STATUS_FILE_ERROR;
1163 if (errno != ENOENT) {
1164 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1166 ret = NOTMUCH_STATUS_FILE_ERROR;
1170 /* Unconditionally attempt to remove old work-in-progress database (if
1171 * any). This is "protected" by database lock. If this fails due to write
1172 * errors (etc), the following code will fail and provide error message.
1174 (void) rmtree (compact_xapian_path);
1177 NotmuchCompactor compactor (status_cb, closure);
1179 compactor.set_renumber (false);
1180 compactor.add_source (xapian_path);
1181 compactor.set_destdir (compact_xapian_path);
1182 compactor.compact ();
1183 } catch (const Xapian::Error &error) {
1184 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1185 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1189 if (rename (xapian_path, backup_path)) {
1190 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1191 xapian_path, backup_path, strerror (errno));
1192 ret = NOTMUCH_STATUS_FILE_ERROR;
1196 if (rename (compact_xapian_path, xapian_path)) {
1197 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1198 compact_xapian_path, xapian_path, strerror (errno));
1199 ret = NOTMUCH_STATUS_FILE_ERROR;
1203 if (! keep_backup) {
1204 if (rmtree (backup_path)) {
1205 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1206 backup_path, strerror (errno));
1207 ret = NOTMUCH_STATUS_FILE_ERROR;
1214 notmuch_status_t ret2;
1216 const char *str = notmuch_database_status_string (notmuch);
1217 if (status_cb && str)
1218 status_cb (str, closure);
1220 ret2 = notmuch_database_destroy (notmuch);
1222 /* don't clobber previous error status */
1223 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1227 talloc_free (local);
1233 notmuch_database_compact (unused (const char *path),
1234 unused (const char *backup_path),
1235 unused (notmuch_compact_status_cb_t status_cb),
1236 unused (void *closure))
1238 _notmuch_database_log (notmuch, "notmuch was compiled against a xapian version lacking compaction support.\n");
1239 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1244 notmuch_database_destroy (notmuch_database_t *notmuch)
1246 notmuch_status_t status;
1248 status = notmuch_database_close (notmuch);
1249 talloc_free (notmuch);
1255 notmuch_database_get_path (notmuch_database_t *notmuch)
1257 return notmuch->path;
1261 notmuch_database_get_version (notmuch_database_t *notmuch)
1263 unsigned int version;
1264 string version_string;
1268 version_string = notmuch->xapian_db->get_metadata ("version");
1269 if (version_string.empty ())
1272 str = version_string.c_str ();
1273 if (str == NULL || *str == '\0')
1276 version = strtoul (str, &end, 10);
1278 INTERNAL_ERROR ("Malformed database version: %s", str);
1284 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1286 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1287 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1288 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1291 static volatile sig_atomic_t do_progress_notify = 0;
1294 handle_sigalrm (unused (int signal))
1296 do_progress_notify = 1;
1299 /* Upgrade the current database.
1301 * After opening a database in read-write mode, the client should
1302 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1303 * if so, upgrade with this function before making any modifications.
1305 * The optional progress_notify callback can be used by the caller to
1306 * provide progress indication to the user. If non-NULL it will be
1307 * called periodically with 'count' as the number of messages upgraded
1308 * so far and 'total' the overall number of messages that will be
1312 notmuch_database_upgrade (notmuch_database_t *notmuch,
1313 void (*progress_notify) (void *closure,
1317 void *local = talloc_new (NULL);
1318 Xapian::TermIterator t, t_end;
1319 Xapian::WritableDatabase *db;
1320 struct sigaction action;
1321 struct itimerval timerval;
1322 notmuch_bool_t timer_is_active = FALSE;
1323 enum _notmuch_features target_features, new_features;
1324 notmuch_status_t status;
1325 notmuch_private_status_t private_status;
1326 unsigned int count = 0, total = 0;
1328 status = _notmuch_database_ensure_writable (notmuch);
1332 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1334 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1335 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1337 if (! notmuch_database_needs_upgrade (notmuch))
1338 return NOTMUCH_STATUS_SUCCESS;
1340 if (progress_notify) {
1341 /* Set up our handler for SIGALRM */
1342 memset (&action, 0, sizeof (struct sigaction));
1343 action.sa_handler = handle_sigalrm;
1344 sigemptyset (&action.sa_mask);
1345 action.sa_flags = SA_RESTART;
1346 sigaction (SIGALRM, &action, NULL);
1348 /* Then start a timer to send SIGALRM once per second. */
1349 timerval.it_interval.tv_sec = 1;
1350 timerval.it_interval.tv_usec = 0;
1351 timerval.it_value.tv_sec = 1;
1352 timerval.it_value.tv_usec = 0;
1353 setitimer (ITIMER_REAL, &timerval, NULL);
1355 timer_is_active = TRUE;
1358 /* Figure out how much total work we need to do. */
1360 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1361 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1362 total += notmuch_query_count_messages (query);
1363 notmuch_query_destroy (query);
1365 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1366 t_end = db->allterms_end ("XTIMESTAMP");
1367 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1370 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1371 /* The ghost message upgrade converts all thread_id_*
1372 * metadata values into ghost message documents. */
1373 t_end = db->metadata_keys_end ("thread_id_");
1374 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1378 /* Perform the upgrade in a transaction. */
1379 db->begin_transaction (true);
1381 /* Set the target features so we write out changes in the desired
1383 notmuch->features = target_features;
1385 /* Perform per-message upgrades. */
1387 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1388 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1389 notmuch_messages_t *messages;
1390 notmuch_message_t *message;
1393 for (messages = notmuch_query_search_messages (query);
1394 notmuch_messages_valid (messages);
1395 notmuch_messages_move_to_next (messages))
1397 if (do_progress_notify) {
1398 progress_notify (closure, (double) count / total);
1399 do_progress_notify = 0;
1402 message = notmuch_messages_get (messages);
1404 /* Before version 1, each message document had its
1405 * filename in the data field. Copy that into the new
1406 * format by calling notmuch_message_add_filename.
1408 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1409 filename = _notmuch_message_talloc_copy_data (message);
1410 if (filename && *filename != '\0') {
1411 _notmuch_message_add_filename (message, filename);
1412 _notmuch_message_clear_data (message);
1414 talloc_free (filename);
1417 /* Prior to version 2, the "folder:" prefix was
1418 * probabilistic and stemmed. Change it to the current
1419 * boolean prefix. Add "path:" prefixes while at it.
1421 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1422 _notmuch_message_upgrade_folder (message);
1424 _notmuch_message_sync (message);
1426 notmuch_message_destroy (message);
1431 notmuch_query_destroy (query);
1434 /* Perform per-directory upgrades. */
1436 /* Before version 1 we stored directory timestamps in
1437 * XTIMESTAMP documents instead of the current XDIRECTORY
1438 * documents. So copy those as well. */
1439 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1440 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1442 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1446 Xapian::PostingIterator p, p_end;
1447 std::string term = *t;
1449 p_end = notmuch->xapian_db->postlist_end (term);
1451 for (p = notmuch->xapian_db->postlist_begin (term);
1455 Xapian::Document document;
1457 notmuch_directory_t *directory;
1459 if (do_progress_notify) {
1460 progress_notify (closure, (double) count / total);
1461 do_progress_notify = 0;
1464 document = find_document_for_doc_id (notmuch, *p);
1465 mtime = Xapian::sortable_unserialise (
1466 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1468 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1469 NOTMUCH_FIND_CREATE, &status);
1470 notmuch_directory_set_mtime (directory, mtime);
1471 notmuch_directory_destroy (directory);
1473 db->delete_document (*p);
1480 /* Perform metadata upgrades. */
1482 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1483 * messages were stored as database metadata. Change these to
1486 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1487 notmuch_message_t *message;
1488 std::string message_id, thread_id;
1490 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1491 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1493 if (do_progress_notify) {
1494 progress_notify (closure, (double) count / total);
1495 do_progress_notify = 0;
1498 message_id = (*t).substr (
1499 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1500 thread_id = db->get_metadata (*t);
1502 /* Create ghost message */
1503 message = _notmuch_message_create_for_message_id (
1504 notmuch, message_id.c_str (), &private_status);
1505 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1506 /* Document already exists; ignore the stored thread ID */
1507 } else if (private_status ==
1508 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1509 private_status = _notmuch_message_initialize_ghost (
1510 message, thread_id.c_str ());
1511 if (! private_status)
1512 _notmuch_message_sync (message);
1515 if (private_status) {
1516 _notmuch_database_log (notmuch,
1517 "Upgrade failed while creating ghost messages.\n");
1518 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1522 /* Clear saved metadata thread ID */
1523 db->set_metadata (*t, "");
1529 status = NOTMUCH_STATUS_SUCCESS;
1530 db->set_metadata ("features", _print_features (local, notmuch->features));
1531 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1534 if (status == NOTMUCH_STATUS_SUCCESS)
1535 db->commit_transaction ();
1537 db->cancel_transaction ();
1539 if (timer_is_active) {
1540 /* Now stop the timer. */
1541 timerval.it_interval.tv_sec = 0;
1542 timerval.it_interval.tv_usec = 0;
1543 timerval.it_value.tv_sec = 0;
1544 timerval.it_value.tv_usec = 0;
1545 setitimer (ITIMER_REAL, &timerval, NULL);
1547 /* And disable the signal handler. */
1548 action.sa_handler = SIG_IGN;
1549 sigaction (SIGALRM, &action, NULL);
1552 talloc_free (local);
1557 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1559 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1560 notmuch->atomic_nesting > 0)
1564 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1565 } catch (const Xapian::Error &error) {
1566 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1567 error.get_msg().c_str());
1568 notmuch->exception_reported = TRUE;
1569 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1573 notmuch->atomic_nesting++;
1574 return NOTMUCH_STATUS_SUCCESS;
1578 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1580 Xapian::WritableDatabase *db;
1582 if (notmuch->atomic_nesting == 0)
1583 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1585 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1586 notmuch->atomic_nesting > 1)
1589 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1591 db->commit_transaction ();
1593 /* This is a hack for testing. Xapian never flushes on a
1594 * non-flushed commit, even if the flush threshold is 1.
1595 * However, we rely on flushing to test atomicity. */
1596 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1597 if (thresh && atoi (thresh) == 1)
1599 } catch (const Xapian::Error &error) {
1600 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1601 error.get_msg().c_str());
1602 notmuch->exception_reported = TRUE;
1603 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1607 notmuch->atomic_nesting--;
1608 return NOTMUCH_STATUS_SUCCESS;
1611 /* We allow the user to use arbitrarily long paths for directories. But
1612 * we have a term-length limit. So if we exceed that, we'll use the
1613 * SHA-1 of the path for the database term.
1615 * Note: This function may return the original value of 'path'. If it
1616 * does not, then the caller is responsible to free() the returned
1620 _notmuch_database_get_directory_db_path (const char *path)
1622 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1624 if (term_len > NOTMUCH_TERM_MAX)
1625 return _notmuch_sha1_of_string (path);
1630 /* Given a path, split it into two parts: the directory part is all
1631 * components except for the last, and the basename is that last
1632 * component. Getting the return-value for either part is optional
1633 * (the caller can pass NULL).
1635 * The original 'path' can represent either a regular file or a
1636 * directory---the splitting will be carried out in the same way in
1637 * either case. Trailing slashes on 'path' will be ignored, and any
1638 * cases of multiple '/' characters appearing in series will be
1639 * treated as a single '/'.
1641 * Allocation (if any) will have 'ctx' as the talloc owner. But
1642 * pointers will be returned within the original path string whenever
1645 * Note: If 'path' is non-empty and contains no non-trailing slash,
1646 * (that is, consists of a filename with no parent directory), then
1647 * the directory returned will be an empty string. However, if 'path'
1648 * is an empty string, then both directory and basename will be
1652 _notmuch_database_split_path (void *ctx,
1654 const char **directory,
1655 const char **basename)
1659 if (path == NULL || *path == '\0') {
1664 return NOTMUCH_STATUS_SUCCESS;
1667 /* Find the last slash (not counting a trailing slash), if any. */
1669 slash = path + strlen (path) - 1;
1671 /* First, skip trailing slashes. */
1672 while (slash != path) {
1679 /* Then, find a slash. */
1680 while (slash != path) {
1690 /* Finally, skip multiple slashes. */
1691 while (slash != path) {
1698 if (slash == path) {
1700 *directory = talloc_strdup (ctx, "");
1705 *directory = talloc_strndup (ctx, path, slash - path + 1);
1708 return NOTMUCH_STATUS_SUCCESS;
1711 /* Find the document ID of the specified directory.
1713 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1714 * created if one does not exist for 'path'. Otherwise, if the
1715 * directory document does not exist, this sets *directory_id to
1716 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1719 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1721 notmuch_find_flags_t flags,
1722 unsigned int *directory_id)
1724 notmuch_directory_t *directory;
1725 notmuch_status_t status;
1729 return NOTMUCH_STATUS_SUCCESS;
1732 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1733 if (status || !directory) {
1738 *directory_id = _notmuch_directory_get_document_id (directory);
1740 notmuch_directory_destroy (directory);
1742 return NOTMUCH_STATUS_SUCCESS;
1746 _notmuch_database_get_directory_path (void *ctx,
1747 notmuch_database_t *notmuch,
1748 unsigned int doc_id)
1750 Xapian::Document document;
1752 document = find_document_for_doc_id (notmuch, doc_id);
1754 return talloc_strdup (ctx, document.get_data ().c_str ());
1757 /* Given a legal 'filename' for the database, (either relative to
1758 * database path or absolute with initial components identical to
1759 * database path), return a new string (with 'ctx' as the talloc
1760 * owner) suitable for use as a direntry term value.
1762 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1763 * will be created in the database as needed. Otherwise, if the
1764 * necessary directory documents do not exist, this sets
1765 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1768 _notmuch_database_filename_to_direntry (void *ctx,
1769 notmuch_database_t *notmuch,
1770 const char *filename,
1771 notmuch_find_flags_t flags,
1774 const char *relative, *directory, *basename;
1775 Xapian::docid directory_id;
1776 notmuch_status_t status;
1778 relative = _notmuch_database_relative_path (notmuch, filename);
1780 status = _notmuch_database_split_path (ctx, relative,
1781 &directory, &basename);
1785 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1787 if (status || directory_id == (unsigned int)-1) {
1792 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1794 return NOTMUCH_STATUS_SUCCESS;
1797 /* Given a legal 'path' for the database, return the relative path.
1799 * The return value will be a pointer to the original path contents,
1800 * and will be either the original string (if 'path' was relative) or
1801 * a portion of the string (if path was absolute and begins with the
1805 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1808 const char *db_path, *relative;
1809 unsigned int db_path_len;
1811 db_path = notmuch_database_get_path (notmuch);
1812 db_path_len = strlen (db_path);
1816 if (*relative == '/') {
1817 while (*relative == '/' && *(relative+1) == '/')
1820 if (strncmp (relative, db_path, db_path_len) == 0)
1822 relative += db_path_len;
1823 while (*relative == '/')
1832 notmuch_database_get_directory (notmuch_database_t *notmuch,
1834 notmuch_directory_t **directory)
1836 notmuch_status_t status;
1838 if (directory == NULL)
1839 return NOTMUCH_STATUS_NULL_POINTER;
1843 *directory = _notmuch_directory_create (notmuch, path,
1844 NOTMUCH_FIND_LOOKUP, &status);
1845 } catch (const Xapian::Error &error) {
1846 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1847 error.get_msg().c_str());
1848 notmuch->exception_reported = TRUE;
1849 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1854 /* Allocate a document ID that satisfies the following criteria:
1856 * 1. The ID does not exist for any document in the Xapian database
1858 * 2. The ID was not previously returned from this function
1860 * 3. The ID is the smallest integer satisfying (1) and (2)
1862 * This function will trigger an internal error if these constraints
1863 * cannot all be satisfied, (that is, the pool of available document
1864 * IDs has been exhausted).
1867 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1869 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1871 notmuch->last_doc_id++;
1873 if (notmuch->last_doc_id == 0)
1874 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1876 return notmuch->last_doc_id;
1880 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1882 /* 16 bytes (+ terminator) for hexadecimal representation of
1883 * a 64-bit integer. */
1884 static char thread_id[17];
1885 Xapian::WritableDatabase *db;
1887 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1889 notmuch->last_thread_id++;
1891 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1893 db->set_metadata ("last_thread_id", thread_id);
1899 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1901 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1902 message_id = _notmuch_message_id_compressed (ctx, message_id);
1904 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1908 static notmuch_status_t
1909 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1911 const char *message_id,
1912 const char **thread_id_ret);
1914 /* Find the thread ID to which the message with 'message_id' belongs.
1916 * Note: 'thread_id_ret' must not be NULL!
1917 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1920 * Note: If there is no message in the database with the given
1921 * 'message_id' then a new thread_id will be allocated for this
1922 * message ID and stored in the database metadata so that the
1923 * thread ID can be looked up if the message is added to the database
1926 static notmuch_status_t
1927 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1929 const char *message_id,
1930 const char **thread_id_ret)
1932 notmuch_private_status_t status;
1933 notmuch_message_t *message;
1935 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
1936 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
1939 /* Look for this message (regular or ghost) */
1940 message = _notmuch_message_create_for_message_id (
1941 notmuch, message_id, &status);
1942 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1943 /* Message exists */
1944 *thread_id_ret = talloc_steal (
1945 ctx, notmuch_message_get_thread_id (message));
1946 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1947 /* Message did not exist. Give it a fresh thread ID and
1948 * populate this message as a ghost message. */
1949 *thread_id_ret = talloc_strdup (
1950 ctx, _notmuch_database_generate_thread_id (notmuch));
1951 if (! *thread_id_ret) {
1952 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
1954 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
1956 /* Commit the new ghost message */
1957 _notmuch_message_sync (message);
1960 /* Create failed. Fall through. */
1963 notmuch_message_destroy (message);
1965 return COERCE_STATUS (status, "Error creating ghost message");
1968 /* Pre-ghost messages _resolve_message_id_to_thread_id */
1969 static notmuch_status_t
1970 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1972 const char *message_id,
1973 const char **thread_id_ret)
1975 notmuch_status_t status;
1976 notmuch_message_t *message;
1977 string thread_id_string;
1979 Xapian::WritableDatabase *db;
1981 status = notmuch_database_find_message (notmuch, message_id, &message);
1987 *thread_id_ret = talloc_steal (ctx,
1988 notmuch_message_get_thread_id (message));
1990 notmuch_message_destroy (message);
1992 return NOTMUCH_STATUS_SUCCESS;
1995 /* Message has not been seen yet.
1997 * We may have seen a reference to it already, in which case, we
1998 * can return the thread ID stored in the metadata. Otherwise, we
1999 * generate a new thread ID and store it there.
2001 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2002 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2003 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2005 if (thread_id_string.empty()) {
2006 *thread_id_ret = talloc_strdup (ctx,
2007 _notmuch_database_generate_thread_id (notmuch));
2008 db->set_metadata (metadata_key, *thread_id_ret);
2010 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2013 talloc_free (metadata_key);
2015 return NOTMUCH_STATUS_SUCCESS;
2018 static notmuch_status_t
2019 _merge_threads (notmuch_database_t *notmuch,
2020 const char *winner_thread_id,
2021 const char *loser_thread_id)
2023 Xapian::PostingIterator loser, loser_end;
2024 notmuch_message_t *message = NULL;
2025 notmuch_private_status_t private_status;
2026 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2028 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2030 for ( ; loser != loser_end; loser++) {
2031 message = _notmuch_message_create (notmuch, notmuch,
2032 *loser, &private_status);
2033 if (message == NULL) {
2034 ret = COERCE_STATUS (private_status,
2035 "Cannot find document for doc_id from query");
2039 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2040 _notmuch_message_add_term (message, "thread", winner_thread_id);
2041 _notmuch_message_sync (message);
2043 notmuch_message_destroy (message);
2049 notmuch_message_destroy (message);
2055 _my_talloc_free_for_g_hash (void *ptr)
2060 static notmuch_status_t
2061 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2062 notmuch_message_t *message,
2063 notmuch_message_file_t *message_file,
2064 const char **thread_id)
2066 GHashTable *parents = NULL;
2067 const char *refs, *in_reply_to, *in_reply_to_message_id;
2068 const char *last_ref_message_id, *this_message_id;
2069 GList *l, *keys = NULL;
2070 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2072 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2073 _my_talloc_free_for_g_hash, NULL);
2074 this_message_id = notmuch_message_get_message_id (message);
2076 refs = _notmuch_message_file_get_header (message_file, "references");
2077 last_ref_message_id = parse_references (message,
2081 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2082 in_reply_to_message_id = parse_references (message,
2084 parents, in_reply_to);
2086 /* For the parent of this message, use the last message ID of the
2087 * References header, if available. If not, fall back to the
2088 * first message ID in the In-Reply-To header. */
2089 if (last_ref_message_id) {
2090 _notmuch_message_add_term (message, "replyto",
2091 last_ref_message_id);
2092 } else if (in_reply_to_message_id) {
2093 _notmuch_message_add_term (message, "replyto",
2094 in_reply_to_message_id);
2097 keys = g_hash_table_get_keys (parents);
2098 for (l = keys; l; l = l->next) {
2099 char *parent_message_id;
2100 const char *parent_thread_id = NULL;
2102 parent_message_id = (char *) l->data;
2104 _notmuch_message_add_term (message, "reference",
2107 ret = _resolve_message_id_to_thread_id (notmuch,
2114 if (*thread_id == NULL) {
2115 *thread_id = talloc_strdup (message, parent_thread_id);
2116 _notmuch_message_add_term (message, "thread", *thread_id);
2117 } else if (strcmp (*thread_id, parent_thread_id)) {
2118 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2128 g_hash_table_unref (parents);
2133 static notmuch_status_t
2134 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2135 notmuch_message_t *message,
2136 const char **thread_id)
2138 const char *message_id = notmuch_message_get_message_id (message);
2139 Xapian::PostingIterator child, children_end;
2140 notmuch_message_t *child_message = NULL;
2141 const char *child_thread_id;
2142 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2143 notmuch_private_status_t private_status;
2145 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2147 for ( ; child != children_end; child++) {
2149 child_message = _notmuch_message_create (message, notmuch,
2150 *child, &private_status);
2151 if (child_message == NULL) {
2152 ret = COERCE_STATUS (private_status,
2153 "Cannot find document for doc_id from query");
2157 child_thread_id = notmuch_message_get_thread_id (child_message);
2158 if (*thread_id == NULL) {
2159 *thread_id = talloc_strdup (message, child_thread_id);
2160 _notmuch_message_add_term (message, "thread", *thread_id);
2161 } else if (strcmp (*thread_id, child_thread_id)) {
2162 _notmuch_message_remove_term (child_message, "reference",
2164 _notmuch_message_sync (child_message);
2165 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2170 notmuch_message_destroy (child_message);
2171 child_message = NULL;
2176 notmuch_message_destroy (child_message);
2181 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2183 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2184 notmuch_message_t *message)
2186 const char *message_id;
2190 message_id = notmuch_message_get_message_id (message);
2191 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2193 /* Check if we have already seen related messages to this one.
2194 * If we have then use the thread_id that we stored at that time.
2196 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2197 if (stored_id.empty ()) {
2200 Xapian::WritableDatabase *db;
2202 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2204 /* Clear the metadata for this message ID. We don't need it
2206 db->set_metadata (metadata_key, "");
2208 return talloc_strdup (ctx, stored_id.c_str ());
2212 /* Given a blank or ghost 'message' and its corresponding
2213 * 'message_file' link it to existing threads in the database.
2215 * First, if is_ghost, this retrieves the thread ID already stored in
2216 * the message (which will be the case if a message was previously
2217 * added that referenced this one). If the message is blank
2218 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2219 * later in this function). If the database does not support ghost
2220 * messages, this checks for a thread ID stored in database metadata
2221 * for this message ID.
2223 * Second, we look at 'message_file' and its link-relevant headers
2224 * (References and In-Reply-To) for message IDs.
2226 * Finally, we look in the database for existing message that
2227 * reference 'message'.
2229 * In all cases, we assign to the current message the first thread ID
2230 * found. We will also merge any existing, distinct threads where this
2231 * message belongs to both, (which is not uncommon when messages are
2232 * processed out of order).
2234 * Finally, if no thread ID has been found through referenced messages, we
2235 * call _notmuch_message_generate_thread_id to generate a new thread
2236 * ID. This should only happen for new, top-level messages, (no
2237 * References or In-Reply-To header in this message, and no previously
2238 * added message refers to this message).
2240 static notmuch_status_t
2241 _notmuch_database_link_message (notmuch_database_t *notmuch,
2242 notmuch_message_t *message,
2243 notmuch_message_file_t *message_file,
2244 notmuch_bool_t is_ghost)
2246 void *local = talloc_new (NULL);
2247 notmuch_status_t status;
2248 const char *thread_id = NULL;
2250 /* Check if the message already had a thread ID */
2251 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2253 thread_id = notmuch_message_get_thread_id (message);
2255 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2257 _notmuch_message_add_term (message, "thread", thread_id);
2260 status = _notmuch_database_link_message_to_parents (notmuch, message,
2266 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2267 /* In general, it shouldn't be necessary to link children,
2268 * since the earlier indexing of those children will have
2269 * stored a thread ID for the missing parent. However, prior
2270 * to ghost messages, these stored thread IDs were NOT
2271 * rewritten during thread merging (and there was no
2272 * performant way to do so), so if indexed children were
2273 * pulled into a different thread ID by a merge, it was
2274 * necessary to pull them *back* into the stored thread ID of
2275 * the parent. With ghost messages, we just rewrite the
2276 * stored thread IDs during merging, so this workaround isn't
2278 status = _notmuch_database_link_message_to_children (notmuch, message,
2284 /* If not part of any existing thread, generate a new thread ID. */
2285 if (thread_id == NULL) {
2286 thread_id = _notmuch_database_generate_thread_id (notmuch);
2288 _notmuch_message_add_term (message, "thread", thread_id);
2292 talloc_free (local);
2298 notmuch_database_add_message (notmuch_database_t *notmuch,
2299 const char *filename,
2300 notmuch_message_t **message_ret)
2302 notmuch_message_file_t *message_file;
2303 notmuch_message_t *message = NULL;
2304 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2305 notmuch_private_status_t private_status;
2306 notmuch_bool_t is_ghost = false;
2308 const char *date, *header;
2309 const char *from, *to, *subject;
2310 char *message_id = NULL;
2313 *message_ret = NULL;
2315 ret = _notmuch_database_ensure_writable (notmuch);
2319 message_file = _notmuch_message_file_open (notmuch, filename);
2320 if (message_file == NULL)
2321 return NOTMUCH_STATUS_FILE_ERROR;
2323 /* Adding a message may change many documents. Do this all
2325 ret = notmuch_database_begin_atomic (notmuch);
2329 /* Parse message up front to get better error status. */
2330 ret = _notmuch_message_file_parse (message_file);
2335 /* Before we do any real work, (especially before doing a
2336 * potential SHA-1 computation on the entire file's contents),
2337 * let's make sure that what we're looking at looks like an
2338 * actual email message.
2340 from = _notmuch_message_file_get_header (message_file, "from");
2341 subject = _notmuch_message_file_get_header (message_file, "subject");
2342 to = _notmuch_message_file_get_header (message_file, "to");
2344 if ((from == NULL || *from == '\0') &&
2345 (subject == NULL || *subject == '\0') &&
2346 (to == NULL || *to == '\0'))
2348 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2352 /* Now that we're sure it's mail, the first order of business
2353 * is to find a message ID (or else create one ourselves). */
2355 header = _notmuch_message_file_get_header (message_file, "message-id");
2356 if (header && *header != '\0') {
2357 message_id = _parse_message_id (message_file, header, NULL);
2359 /* So the header value isn't RFC-compliant, but it's
2360 * better than no message-id at all. */
2361 if (message_id == NULL)
2362 message_id = talloc_strdup (message_file, header);
2365 if (message_id == NULL ) {
2366 /* No message-id at all, let's generate one by taking a
2367 * hash over the file's contents. */
2368 char *sha1 = _notmuch_sha1_of_file (filename);
2370 /* If that failed too, something is really wrong. Give up. */
2372 ret = NOTMUCH_STATUS_FILE_ERROR;
2376 message_id = talloc_asprintf (message_file,
2377 "notmuch-sha1-%s", sha1);
2381 /* Now that we have a message ID, we get a message object,
2382 * (which may or may not reference an existing document in the
2385 message = _notmuch_message_create_for_message_id (notmuch,
2389 talloc_free (message_id);
2391 if (message == NULL) {
2392 ret = COERCE_STATUS (private_status,
2393 "Unexpected status value from _notmuch_message_create_for_message_id");
2397 _notmuch_message_add_filename (message, filename);
2399 /* Is this a newly created message object or a ghost
2400 * message? We have to be slightly careful: if this is a
2401 * blank message, it's not safe to call
2402 * notmuch_message_get_flag yet. */
2403 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2404 (is_ghost = notmuch_message_get_flag (
2405 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2406 _notmuch_message_add_term (message, "type", "mail");
2408 /* Convert ghost message to a regular message */
2409 _notmuch_message_remove_term (message, "type", "ghost");
2411 ret = _notmuch_database_link_message (notmuch, message,
2412 message_file, is_ghost);
2416 date = _notmuch_message_file_get_header (message_file, "date");
2417 _notmuch_message_set_header_values (message, date, from, subject);
2419 ret = _notmuch_message_index_file (message, message_file);
2423 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2426 _notmuch_message_sync (message);
2427 } catch (const Xapian::Error &error) {
2428 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2429 error.get_msg().c_str());
2430 notmuch->exception_reported = TRUE;
2431 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2437 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2438 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2439 *message_ret = message;
2441 notmuch_message_destroy (message);
2445 _notmuch_message_file_close (message_file);
2447 ret2 = notmuch_database_end_atomic (notmuch);
2448 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2449 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2450 ret2 != NOTMUCH_STATUS_SUCCESS)
2457 notmuch_database_remove_message (notmuch_database_t *notmuch,
2458 const char *filename)
2460 notmuch_status_t status;
2461 notmuch_message_t *message;
2463 status = notmuch_database_find_message_by_filename (notmuch, filename,
2466 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2467 status = _notmuch_message_remove_filename (message, filename);
2468 if (status == NOTMUCH_STATUS_SUCCESS)
2469 _notmuch_message_delete (message);
2470 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2471 _notmuch_message_sync (message);
2473 notmuch_message_destroy (message);
2480 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2481 const char *filename,
2482 notmuch_message_t **message_ret)
2485 const char *prefix = _find_prefix ("file-direntry");
2486 char *direntry, *term;
2487 Xapian::PostingIterator i, end;
2488 notmuch_status_t status;
2490 if (message_ret == NULL)
2491 return NOTMUCH_STATUS_NULL_POINTER;
2493 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2494 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2496 /* return NULL on any failure */
2497 *message_ret = NULL;
2499 local = talloc_new (notmuch);
2502 status = _notmuch_database_filename_to_direntry (
2503 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2504 if (status || !direntry)
2507 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2509 find_doc_ids_for_term (notmuch, term, &i, &end);
2512 notmuch_private_status_t private_status;
2514 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2516 if (*message_ret == NULL)
2517 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2519 } catch (const Xapian::Error &error) {
2520 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2521 error.get_msg().c_str());
2522 notmuch->exception_reported = TRUE;
2523 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2527 talloc_free (local);
2529 if (status && *message_ret) {
2530 notmuch_message_destroy (*message_ret);
2531 *message_ret = NULL;
2536 notmuch_string_list_t *
2537 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2538 Xapian::TermIterator &end,
2541 int prefix_len = strlen (prefix);
2542 notmuch_string_list_t *list;
2544 list = _notmuch_string_list_create (ctx);
2545 if (unlikely (list == NULL))
2548 for (i.skip_to (prefix); i != end; i++) {
2549 /* Terminate loop at first term without desired prefix. */
2550 if (strncmp ((*i).c_str (), prefix, prefix_len))
2553 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2560 notmuch_database_get_all_tags (notmuch_database_t *db)
2562 Xapian::TermIterator i, end;
2563 notmuch_string_list_t *tags;
2566 i = db->xapian_db->allterms_begin();
2567 end = db->xapian_db->allterms_end();
2568 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2569 _find_prefix ("tag"));
2570 _notmuch_string_list_sort (tags);
2571 return _notmuch_tags_create (db, tags);
2572 } catch (const Xapian::Error &error) {
2573 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2574 error.get_msg().c_str());
2575 db->exception_reported = TRUE;
2581 notmuch_database_status_string (notmuch_database_t *notmuch)
2583 return notmuch->status_string;