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"
28 #include <glib.h> /* g_free, GPtrArray, GHashTable */
29 #include <glib-object.h> /* g_type_init */
31 #include <gmime/gmime.h> /* g_mime_init */
35 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
42 #define NOTMUCH_DATABASE_VERSION 1
44 #define STRINGIFY(s) _SUB_STRINGIFY(s)
45 #define _SUB_STRINGIFY(s) #s
47 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
49 * We currently have two different types of documents (mail and
50 * directory) and also some metadata.
54 * A mail document is associated with a particular email message file
55 * on disk. It is indexed with the following prefixed terms which the
56 * database uses to construct threads, etc.:
58 * Single terms of given prefix:
62 * id: Unique ID of mail. This is from the Message-ID header
63 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
64 * If it's present and too long, then we use
65 * "notmuch-sha1-<sha1_sum_of_message_id>".
66 * If this header is not present, we use
67 * "notmuch-sha1-<sha1_sum_of_entire_file>".
69 * thread: The ID of the thread to which the mail belongs
71 * replyto: The ID from the In-Reply-To header of the mail (if any).
73 * Multiple terms of given prefix:
75 * reference: All message IDs from In-Reply-To and References
76 * headers in the message.
78 * tag: Any tags associated with this message by the user.
80 * file-direntry: A colon-separated pair of values
81 * (INTEGER:STRING), where INTEGER is the
82 * document ID of a directory document, and
83 * STRING is the name of a file within that
84 * directory for this mail message.
86 * A mail document also has four values:
88 * TIMESTAMP: The time_t value corresponding to the message's
91 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
93 * FROM: The value of the "From" header
95 * SUBJECT: The value of the "Subject" header
97 * In addition, terms from the content of the message are added with
98 * "from", "to", "attachment", and "subject" prefixes for use by the
99 * user in searching. Similarly, terms from the path of the mail
100 * message are added with a "folder" prefix. But the database doesn't
101 * really care itself about any of these.
103 * The data portion of a mail document is empty.
107 * A directory document is used by a client of the notmuch library to
108 * maintain data necessary to allow for efficient polling of mail
111 * All directory documents contain one term:
113 * directory: The directory path (relative to the database path)
114 * Or the SHA1 sum of the directory path (if the
115 * path itself is too long to fit in a Xapian
118 * And all directory documents for directories other than top-level
119 * directories also contain the following term:
121 * directory-direntry: A colon-separated pair of values
122 * (INTEGER:STRING), where INTEGER is the
123 * document ID of the parent directory
124 * document, and STRING is the name of this
125 * directory within that parent.
127 * All directory documents have a single value:
129 * TIMESTAMP: The mtime of the directory (at last scan)
131 * The data portion of a directory document contains the path of the
132 * directory (relative to the database path).
136 * Xapian allows us to store arbitrary name-value pairs as
137 * "metadata". We currently use the following metadata names with the
140 * version The database schema version, (which is distinct
141 * from both the notmuch package version (see
142 * notmuch --version) and the libnotmuch library
143 * version. The version is stored as an base-10
144 * ASCII integer. The initial database version
145 * was 1, (though a schema existed before that
146 * were no "version" database value existed at
147 * all). Successive versions are allocated as
148 * changes are made to the database (such as by
149 * indexing new fields).
151 * last_thread_id The last thread ID generated. This is stored
152 * as a 16-byte hexadecimal ASCII representation
153 * of a 64-bit unsigned integer. The first ID
154 * generated is 1 and the value will be
155 * incremented for each thread ID.
157 * thread_id_* A pre-allocated thread ID for a particular
158 * message. This is actually an arbitrarily large
159 * family of metadata name. Any particular name is
160 * formed by concatenating "thread_id_" with a message
161 * ID (or the SHA1 sum of a message ID if it is very
162 * long---see description of 'id' in the mail
163 * document). The value stored is a thread ID.
165 * These thread ID metadata values are stored
166 * whenever a message references a parent message
167 * that does not yet exist in the database. A
168 * thread ID will be allocated and stored, and if
169 * the message is later added, the stored thread
170 * ID will be used (and the metadata value will
173 * Even before a message is added, it's
174 * pre-allocated thread ID is useful so that all
175 * descendant messages that reference this common
176 * parent can be recognized as belonging to the
180 /* With these prefix values we follow the conventions published here:
182 * http://xapian.org/docs/omega/termprefixes.html
184 * as much as makes sense. Note that I took some liberty in matching
185 * the reserved prefix values to notmuch concepts, (for example, 'G'
186 * is documented as "newsGroup (or similar entity - e.g. a web forum
187 * name)", for which I think the thread is the closest analogue in
188 * notmuch. This in spite of the fact that we will eventually be
189 * storing mailing-list messages where 'G' for "mailing list name"
190 * might be even a closer analogue. I'm treating the single-character
191 * prefixes preferentially for core notmuch concepts (which will be
192 * nearly universal to all mail messages).
195 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
197 { "reference", "XREFERENCE" },
198 { "replyto", "XREPLYTO" },
199 { "directory", "XDIRECTORY" },
200 { "file-direntry", "XFDIRENTRY" },
201 { "directory-direntry", "XDDIRENTRY" },
204 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
211 static prefix_t PROBABILISTIC_PREFIX[]= {
214 { "attachment", "XATTACHMENT" },
215 { "subject", "XSUBJECT"},
216 { "folder", "XFOLDER"}
220 _find_prefix (const char *name)
224 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
225 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
226 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
229 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
230 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
231 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
234 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
235 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
236 return PROBABILISTIC_PREFIX[i].prefix;
239 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
245 notmuch_status_to_string (notmuch_status_t status)
248 case NOTMUCH_STATUS_SUCCESS:
249 return "No error occurred";
250 case NOTMUCH_STATUS_OUT_OF_MEMORY:
251 return "Out of memory";
252 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
253 return "Attempt to write to a read-only database";
254 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
255 return "A Xapian exception occurred";
256 case NOTMUCH_STATUS_FILE_ERROR:
257 return "Something went wrong trying to read or write a file";
258 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
259 return "File is not an email";
260 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
261 return "Message ID is identical to a message in database";
262 case NOTMUCH_STATUS_NULL_POINTER:
263 return "Erroneous NULL pointer";
264 case NOTMUCH_STATUS_TAG_TOO_LONG:
265 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
266 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
267 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
268 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
269 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
271 case NOTMUCH_STATUS_LAST_STATUS:
272 return "Unknown error status value";
277 find_doc_ids_for_term (notmuch_database_t *notmuch,
279 Xapian::PostingIterator *begin,
280 Xapian::PostingIterator *end)
282 *begin = notmuch->xapian_db->postlist_begin (term);
284 *end = notmuch->xapian_db->postlist_end (term);
288 find_doc_ids (notmuch_database_t *notmuch,
289 const char *prefix_name,
291 Xapian::PostingIterator *begin,
292 Xapian::PostingIterator *end)
296 term = talloc_asprintf (notmuch, "%s%s",
297 _find_prefix (prefix_name), value);
299 find_doc_ids_for_term (notmuch, term, begin, end);
304 notmuch_private_status_t
305 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
306 const char *prefix_name,
308 unsigned int *doc_id)
310 Xapian::PostingIterator i, end;
312 find_doc_ids (notmuch, prefix_name, value, &i, &end);
316 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
321 #if DEBUG_DATABASE_SANITY
325 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
329 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
332 static Xapian::Document
333 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
335 return notmuch->xapian_db->get_document (doc_id);
338 /* Generate a compressed version of 'message_id' of the form:
340 * notmuch-sha1-<sha1_sum_of_message_id>
343 _message_id_compressed (void *ctx, const char *message_id)
345 char *sha1, *compressed;
347 sha1 = notmuch_sha1_of_string (message_id);
349 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
356 notmuch_database_find_message (notmuch_database_t *notmuch,
357 const char *message_id,
358 notmuch_message_t **message_ret)
360 notmuch_private_status_t status;
363 if (message_ret == NULL)
364 return NOTMUCH_STATUS_NULL_POINTER;
366 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
367 message_id = _message_id_compressed (notmuch, message_id);
370 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
371 message_id, &doc_id);
373 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
376 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
378 if (*message_ret == NULL)
379 return NOTMUCH_STATUS_OUT_OF_MEMORY;
382 return NOTMUCH_STATUS_SUCCESS;
383 } catch (const Xapian::Error &error) {
384 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
385 error.get_msg().c_str());
386 notmuch->exception_reported = TRUE;
388 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
392 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
393 * a (potentially nested) parenthesized sequence with '\' used to
394 * escape any character (including parentheses).
396 * If the sequence to be skipped continues to the end of the string,
397 * then 'str' will be left pointing at the final terminating '\0'
401 skip_space_and_comments (const char **str)
406 while (*s && (isspace (*s) || *s == '(')) {
407 while (*s && isspace (*s))
412 while (*s && nesting) {
415 } else if (*s == ')') {
417 } else if (*s == '\\') {
429 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
430 * comments, and the '<' and '>' delimiters.
432 * If not NULL, then *next will be made to point to the first character
433 * not parsed, (possibly pointing to the final '\0' terminator.
435 * Returns a newly talloc'ed string belonging to 'ctx'.
437 * Returns NULL if there is any error parsing the message-id. */
439 _parse_message_id (void *ctx, const char *message_id, const char **next)
444 if (message_id == NULL || *message_id == '\0')
449 skip_space_and_comments (&s);
451 /* Skip any unstructured text as well. */
452 while (*s && *s != '<')
463 skip_space_and_comments (&s);
466 while (*end && *end != '>')
475 if (end > s && *end == '>')
480 result = talloc_strndup (ctx, s, end - s + 1);
482 /* Finally, collapse any whitespace that is within the message-id
488 for (r = result, len = strlen (r); *r; r++, len--)
489 if (*r == ' ' || *r == '\t')
490 memmove (r, r+1, len);
496 /* Parse a References header value, putting a (talloc'ed under 'ctx')
497 * copy of each referenced message-id into 'hash'.
499 * We explicitly avoid including any reference identical to
500 * 'message_id' in the result (to avoid mass confusion when a single
501 * message references itself cyclically---and yes, mail messages are
502 * not infrequent in the wild that do this---don't ask me why).
505 parse_references (void *ctx,
506 const char *message_id,
512 if (refs == NULL || *refs == '\0')
516 ref = _parse_message_id (ctx, refs, &refs);
518 if (ref && strcmp (ref, message_id))
519 g_hash_table_insert (hash, ref, NULL);
524 notmuch_database_create (const char *path)
526 notmuch_database_t *notmuch = NULL;
527 char *notmuch_path = NULL;
532 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
536 err = stat (path, &st);
538 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
539 path, strerror (errno));
543 if (! S_ISDIR (st.st_mode)) {
544 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
549 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
551 err = mkdir (notmuch_path, 0755);
554 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
555 notmuch_path, strerror (errno));
559 notmuch_database_open (path,
560 NOTMUCH_DATABASE_MODE_READ_WRITE,
562 notmuch_database_upgrade (notmuch, NULL, NULL);
566 talloc_free (notmuch_path);
572 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
574 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
575 fprintf (stderr, "Cannot write to a read-only database.\n");
576 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
579 return NOTMUCH_STATUS_SUCCESS;
583 notmuch_database_open (const char *path,
584 notmuch_database_mode_t mode,
585 notmuch_database_t **database)
587 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
588 void *local = talloc_new (NULL);
589 notmuch_database_t *notmuch = NULL;
590 char *notmuch_path, *xapian_path;
593 unsigned int i, version;
594 static int initialized = 0;
597 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
598 status = NOTMUCH_STATUS_NULL_POINTER;
602 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
603 fprintf (stderr, "Out of memory\n");
604 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
608 err = stat (notmuch_path, &st);
610 fprintf (stderr, "Error opening database at %s: %s\n",
611 notmuch_path, strerror (errno));
612 status = NOTMUCH_STATUS_FILE_ERROR;
616 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
617 fprintf (stderr, "Out of memory\n");
618 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
622 /* Initialize the GLib type system and threads */
625 /* Initialize gmime */
631 notmuch = talloc_zero (NULL, notmuch_database_t);
632 notmuch->exception_reported = FALSE;
633 notmuch->path = talloc_strdup (notmuch, path);
635 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
636 notmuch->path[strlen (notmuch->path) - 1] = '\0';
638 notmuch->needs_upgrade = FALSE;
639 notmuch->mode = mode;
640 notmuch->atomic_nesting = 0;
642 string last_thread_id;
644 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
645 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
646 Xapian::DB_CREATE_OR_OPEN);
647 version = notmuch_database_get_version (notmuch);
649 if (version > NOTMUCH_DATABASE_VERSION) {
651 "Error: Notmuch database at %s\n"
652 " has a newer database format version (%u) than supported by this\n"
653 " version of notmuch (%u). Refusing to open this database in\n"
654 " read-write mode.\n",
655 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
656 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
657 notmuch_database_destroy (notmuch);
659 status = NOTMUCH_STATUS_FILE_ERROR;
663 if (version < NOTMUCH_DATABASE_VERSION)
664 notmuch->needs_upgrade = TRUE;
666 notmuch->xapian_db = new Xapian::Database (xapian_path);
667 version = notmuch_database_get_version (notmuch);
668 if (version > NOTMUCH_DATABASE_VERSION)
671 "Warning: Notmuch database at %s\n"
672 " has a newer database format version (%u) than supported by this\n"
673 " version of notmuch (%u). Some operations may behave incorrectly,\n"
674 " (but the database will not be harmed since it is being opened\n"
675 " in read-only mode).\n",
676 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
680 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
681 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
682 if (last_thread_id.empty ()) {
683 notmuch->last_thread_id = 0;
688 str = last_thread_id.c_str ();
689 notmuch->last_thread_id = strtoull (str, &end, 16);
691 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
694 notmuch->query_parser = new Xapian::QueryParser;
695 notmuch->term_gen = new Xapian::TermGenerator;
696 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
697 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
699 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
700 notmuch->query_parser->set_database (*notmuch->xapian_db);
701 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
702 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
703 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
705 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
706 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
707 notmuch->query_parser->add_boolean_prefix (prefix->name,
711 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
712 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
713 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
715 } catch (const Xapian::Error &error) {
716 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
717 error.get_msg().c_str());
718 notmuch_database_destroy (notmuch);
720 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
729 talloc_free (notmuch);
734 notmuch_database_close (notmuch_database_t *notmuch)
737 if (notmuch->xapian_db != NULL &&
738 notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
739 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
740 } catch (const Xapian::Error &error) {
741 if (! notmuch->exception_reported) {
742 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
743 error.get_msg().c_str());
747 /* Many Xapian objects (and thus notmuch objects) hold references to
748 * the database, so merely deleting the database may not suffice to
749 * close it. Thus, we explicitly close it here. */
750 if (notmuch->xapian_db != NULL) {
752 notmuch->xapian_db->close();
753 } catch (const Xapian::Error &error) {
758 delete notmuch->term_gen;
759 notmuch->term_gen = NULL;
760 delete notmuch->query_parser;
761 notmuch->query_parser = NULL;
762 delete notmuch->xapian_db;
763 notmuch->xapian_db = NULL;
764 delete notmuch->value_range_processor;
765 notmuch->value_range_processor = NULL;
769 notmuch_database_destroy (notmuch_database_t *notmuch)
771 notmuch_database_close (notmuch);
772 talloc_free (notmuch);
776 notmuch_database_get_path (notmuch_database_t *notmuch)
778 return notmuch->path;
782 notmuch_database_get_version (notmuch_database_t *notmuch)
784 unsigned int version;
785 string version_string;
789 version_string = notmuch->xapian_db->get_metadata ("version");
790 if (version_string.empty ())
793 str = version_string.c_str ();
794 if (str == NULL || *str == '\0')
797 version = strtoul (str, &end, 10);
799 INTERNAL_ERROR ("Malformed database version: %s", str);
805 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
807 return notmuch->needs_upgrade;
810 static volatile sig_atomic_t do_progress_notify = 0;
813 handle_sigalrm (unused (int signal))
815 do_progress_notify = 1;
818 /* Upgrade the current database.
820 * After opening a database in read-write mode, the client should
821 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
822 * if so, upgrade with this function before making any modifications.
824 * The optional progress_notify callback can be used by the caller to
825 * provide progress indication to the user. If non-NULL it will be
826 * called periodically with 'count' as the number of messages upgraded
827 * so far and 'total' the overall number of messages that will be
831 notmuch_database_upgrade (notmuch_database_t *notmuch,
832 void (*progress_notify) (void *closure,
836 Xapian::WritableDatabase *db;
837 struct sigaction action;
838 struct itimerval timerval;
839 notmuch_bool_t timer_is_active = FALSE;
840 unsigned int version;
841 notmuch_status_t status;
842 unsigned int count = 0, total = 0;
844 status = _notmuch_database_ensure_writable (notmuch);
848 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
850 version = notmuch_database_get_version (notmuch);
852 if (version >= NOTMUCH_DATABASE_VERSION)
853 return NOTMUCH_STATUS_SUCCESS;
855 if (progress_notify) {
856 /* Setup our handler for SIGALRM */
857 memset (&action, 0, sizeof (struct sigaction));
858 action.sa_handler = handle_sigalrm;
859 sigemptyset (&action.sa_mask);
860 action.sa_flags = SA_RESTART;
861 sigaction (SIGALRM, &action, NULL);
863 /* Then start a timer to send SIGALRM once per second. */
864 timerval.it_interval.tv_sec = 1;
865 timerval.it_interval.tv_usec = 0;
866 timerval.it_value.tv_sec = 1;
867 timerval.it_value.tv_usec = 0;
868 setitimer (ITIMER_REAL, &timerval, NULL);
870 timer_is_active = TRUE;
873 /* Before version 1, each message document had its filename in the
874 * data field. Copy that into the new format by calling
875 * notmuch_message_add_filename.
878 notmuch_query_t *query = notmuch_query_create (notmuch, "");
879 notmuch_messages_t *messages;
880 notmuch_message_t *message;
882 Xapian::TermIterator t, t_end;
884 total = notmuch_query_count_messages (query);
886 for (messages = notmuch_query_search_messages (query);
887 notmuch_messages_valid (messages);
888 notmuch_messages_move_to_next (messages))
890 if (do_progress_notify) {
891 progress_notify (closure, (double) count / total);
892 do_progress_notify = 0;
895 message = notmuch_messages_get (messages);
897 filename = _notmuch_message_talloc_copy_data (message);
898 if (filename && *filename != '\0') {
899 _notmuch_message_add_filename (message, filename);
900 _notmuch_message_sync (message);
902 talloc_free (filename);
904 notmuch_message_destroy (message);
909 notmuch_query_destroy (query);
911 /* Also, before version 1 we stored directory timestamps in
912 * XTIMESTAMP documents instead of the current XDIRECTORY
913 * documents. So copy those as well. */
915 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
917 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
921 Xapian::PostingIterator p, p_end;
922 std::string term = *t;
924 p_end = notmuch->xapian_db->postlist_end (term);
926 for (p = notmuch->xapian_db->postlist_begin (term);
930 Xapian::Document document;
932 notmuch_directory_t *directory;
934 if (do_progress_notify) {
935 progress_notify (closure, (double) count / total);
936 do_progress_notify = 0;
939 document = find_document_for_doc_id (notmuch, *p);
940 mtime = Xapian::sortable_unserialise (
941 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
943 directory = notmuch_database_get_directory (notmuch,
945 notmuch_directory_set_mtime (directory, mtime);
946 notmuch_directory_destroy (directory);
951 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
954 /* Now that the upgrade is complete we can remove the old data
955 * and documents that are no longer needed. */
957 notmuch_query_t *query = notmuch_query_create (notmuch, "");
958 notmuch_messages_t *messages;
959 notmuch_message_t *message;
962 for (messages = notmuch_query_search_messages (query);
963 notmuch_messages_valid (messages);
964 notmuch_messages_move_to_next (messages))
966 if (do_progress_notify) {
967 progress_notify (closure, (double) count / total);
968 do_progress_notify = 0;
971 message = notmuch_messages_get (messages);
973 filename = _notmuch_message_talloc_copy_data (message);
974 if (filename && *filename != '\0') {
975 _notmuch_message_clear_data (message);
976 _notmuch_message_sync (message);
978 talloc_free (filename);
980 notmuch_message_destroy (message);
983 notmuch_query_destroy (query);
987 Xapian::TermIterator t, t_end;
989 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
991 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
995 Xapian::PostingIterator p, p_end;
996 std::string term = *t;
998 p_end = notmuch->xapian_db->postlist_end (term);
1000 for (p = notmuch->xapian_db->postlist_begin (term);
1004 if (do_progress_notify) {
1005 progress_notify (closure, (double) count / total);
1006 do_progress_notify = 0;
1009 db->delete_document (*p);
1014 if (timer_is_active) {
1015 /* Now stop the timer. */
1016 timerval.it_interval.tv_sec = 0;
1017 timerval.it_interval.tv_usec = 0;
1018 timerval.it_value.tv_sec = 0;
1019 timerval.it_value.tv_usec = 0;
1020 setitimer (ITIMER_REAL, &timerval, NULL);
1022 /* And disable the signal handler. */
1023 action.sa_handler = SIG_IGN;
1024 sigaction (SIGALRM, &action, NULL);
1027 return NOTMUCH_STATUS_SUCCESS;
1031 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1033 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1034 notmuch->atomic_nesting > 0)
1038 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1039 } catch (const Xapian::Error &error) {
1040 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1041 error.get_msg().c_str());
1042 notmuch->exception_reported = TRUE;
1043 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1047 notmuch->atomic_nesting++;
1048 return NOTMUCH_STATUS_SUCCESS;
1052 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1054 Xapian::WritableDatabase *db;
1056 if (notmuch->atomic_nesting == 0)
1057 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1059 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1060 notmuch->atomic_nesting > 1)
1063 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1065 db->commit_transaction ();
1067 /* This is a hack for testing. Xapian never flushes on a
1068 * non-flushed commit, even if the flush threshold is 1.
1069 * However, we rely on flushing to test atomicity. */
1070 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1071 if (thresh && atoi (thresh) == 1)
1073 } catch (const Xapian::Error &error) {
1074 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1075 error.get_msg().c_str());
1076 notmuch->exception_reported = TRUE;
1077 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1081 notmuch->atomic_nesting--;
1082 return NOTMUCH_STATUS_SUCCESS;
1085 /* We allow the user to use arbitrarily long paths for directories. But
1086 * we have a term-length limit. So if we exceed that, we'll use the
1087 * SHA-1 of the path for the database term.
1089 * Note: This function may return the original value of 'path'. If it
1090 * does not, then the caller is responsible to free() the returned
1094 _notmuch_database_get_directory_db_path (const char *path)
1096 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1098 if (term_len > NOTMUCH_TERM_MAX)
1099 return notmuch_sha1_of_string (path);
1104 /* Given a path, split it into two parts: the directory part is all
1105 * components except for the last, and the basename is that last
1106 * component. Getting the return-value for either part is optional
1107 * (the caller can pass NULL).
1109 * The original 'path' can represent either a regular file or a
1110 * directory---the splitting will be carried out in the same way in
1111 * either case. Trailing slashes on 'path' will be ignored, and any
1112 * cases of multiple '/' characters appearing in series will be
1113 * treated as a single '/'.
1115 * Allocation (if any) will have 'ctx' as the talloc owner. But
1116 * pointers will be returned within the original path string whenever
1119 * Note: If 'path' is non-empty and contains no non-trailing slash,
1120 * (that is, consists of a filename with no parent directory), then
1121 * the directory returned will be an empty string. However, if 'path'
1122 * is an empty string, then both directory and basename will be
1126 _notmuch_database_split_path (void *ctx,
1128 const char **directory,
1129 const char **basename)
1133 if (path == NULL || *path == '\0') {
1138 return NOTMUCH_STATUS_SUCCESS;
1141 /* Find the last slash (not counting a trailing slash), if any. */
1143 slash = path + strlen (path) - 1;
1145 /* First, skip trailing slashes. */
1146 while (slash != path) {
1153 /* Then, find a slash. */
1154 while (slash != path) {
1164 /* Finally, skip multiple slashes. */
1165 while (slash != path) {
1172 if (slash == path) {
1174 *directory = talloc_strdup (ctx, "");
1179 *directory = talloc_strndup (ctx, path, slash - path + 1);
1182 return NOTMUCH_STATUS_SUCCESS;
1186 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1188 unsigned int *directory_id)
1190 notmuch_directory_t *directory;
1191 notmuch_status_t status;
1195 return NOTMUCH_STATUS_SUCCESS;
1198 directory = _notmuch_directory_create (notmuch, path, &status);
1204 *directory_id = _notmuch_directory_get_document_id (directory);
1206 notmuch_directory_destroy (directory);
1208 return NOTMUCH_STATUS_SUCCESS;
1212 _notmuch_database_get_directory_path (void *ctx,
1213 notmuch_database_t *notmuch,
1214 unsigned int doc_id)
1216 Xapian::Document document;
1218 document = find_document_for_doc_id (notmuch, doc_id);
1220 return talloc_strdup (ctx, document.get_data ().c_str ());
1223 /* Given a legal 'filename' for the database, (either relative to
1224 * database path or absolute with initial components identical to
1225 * database path), return a new string (with 'ctx' as the talloc
1226 * owner) suitable for use as a direntry term value.
1228 * The necessary directory documents will be created in the database
1232 _notmuch_database_filename_to_direntry (void *ctx,
1233 notmuch_database_t *notmuch,
1234 const char *filename,
1237 const char *relative, *directory, *basename;
1238 Xapian::docid directory_id;
1239 notmuch_status_t status;
1241 relative = _notmuch_database_relative_path (notmuch, filename);
1243 status = _notmuch_database_split_path (ctx, relative,
1244 &directory, &basename);
1248 status = _notmuch_database_find_directory_id (notmuch, directory,
1253 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1255 return NOTMUCH_STATUS_SUCCESS;
1258 /* Given a legal 'path' for the database, return the relative path.
1260 * The return value will be a pointer to the original path contents,
1261 * and will be either the original string (if 'path' was relative) or
1262 * a portion of the string (if path was absolute and begins with the
1266 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1269 const char *db_path, *relative;
1270 unsigned int db_path_len;
1272 db_path = notmuch_database_get_path (notmuch);
1273 db_path_len = strlen (db_path);
1277 if (*relative == '/') {
1278 while (*relative == '/' && *(relative+1) == '/')
1281 if (strncmp (relative, db_path, db_path_len) == 0)
1283 relative += db_path_len;
1284 while (*relative == '/')
1292 notmuch_directory_t *
1293 notmuch_database_get_directory (notmuch_database_t *notmuch,
1296 notmuch_status_t status;
1299 return _notmuch_directory_create (notmuch, path, &status);
1300 } catch (const Xapian::Error &error) {
1301 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1302 error.get_msg().c_str());
1303 notmuch->exception_reported = TRUE;
1308 /* Allocate a document ID that satisfies the following criteria:
1310 * 1. The ID does not exist for any document in the Xapian database
1312 * 2. The ID was not previously returned from this function
1314 * 3. The ID is the smallest integer satisfying (1) and (2)
1316 * This function will trigger an internal error if these constraints
1317 * cannot all be satisfied, (that is, the pool of available document
1318 * IDs has been exhausted).
1321 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1323 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1325 notmuch->last_doc_id++;
1327 if (notmuch->last_doc_id == 0)
1328 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1330 return notmuch->last_doc_id;
1334 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1336 /* 16 bytes (+ terminator) for hexadecimal representation of
1337 * a 64-bit integer. */
1338 static char thread_id[17];
1339 Xapian::WritableDatabase *db;
1341 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1343 notmuch->last_thread_id++;
1345 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1347 db->set_metadata ("last_thread_id", thread_id);
1353 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1355 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1356 message_id = _message_id_compressed (ctx, message_id);
1358 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1362 /* Find the thread ID to which the message with 'message_id' belongs.
1364 * Note: 'thread_id_ret' must not be NULL!
1365 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1368 * Note: If there is no message in the database with the given
1369 * 'message_id' then a new thread_id will be allocated for this
1370 * message and stored in the database metadata, (where this same
1371 * thread ID can be looked up if the message is added to the database
1374 static notmuch_status_t
1375 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1377 const char *message_id,
1378 const char **thread_id_ret)
1380 notmuch_status_t status;
1381 notmuch_message_t *message;
1382 string thread_id_string;
1384 Xapian::WritableDatabase *db;
1386 status = notmuch_database_find_message (notmuch, message_id, &message);
1392 *thread_id_ret = talloc_steal (ctx,
1393 notmuch_message_get_thread_id (message));
1395 notmuch_message_destroy (message);
1397 return NOTMUCH_STATUS_SUCCESS;
1400 /* Message has not been seen yet.
1402 * We may have seen a reference to it already, in which case, we
1403 * can return the thread ID stored in the metadata. Otherwise, we
1404 * generate a new thread ID and store it there.
1406 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1407 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1408 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1410 if (thread_id_string.empty()) {
1411 *thread_id_ret = talloc_strdup (ctx,
1412 _notmuch_database_generate_thread_id (notmuch));
1413 db->set_metadata (metadata_key, *thread_id_ret);
1415 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1418 talloc_free (metadata_key);
1420 return NOTMUCH_STATUS_SUCCESS;
1423 static notmuch_status_t
1424 _merge_threads (notmuch_database_t *notmuch,
1425 const char *winner_thread_id,
1426 const char *loser_thread_id)
1428 Xapian::PostingIterator loser, loser_end;
1429 notmuch_message_t *message = NULL;
1430 notmuch_private_status_t private_status;
1431 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1433 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1435 for ( ; loser != loser_end; loser++) {
1436 message = _notmuch_message_create (notmuch, notmuch,
1437 *loser, &private_status);
1438 if (message == NULL) {
1439 ret = COERCE_STATUS (private_status,
1440 "Cannot find document for doc_id from query");
1444 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1445 _notmuch_message_add_term (message, "thread", winner_thread_id);
1446 _notmuch_message_sync (message);
1448 notmuch_message_destroy (message);
1454 notmuch_message_destroy (message);
1460 _my_talloc_free_for_g_hash (void *ptr)
1465 static notmuch_status_t
1466 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1467 notmuch_message_t *message,
1468 notmuch_message_file_t *message_file,
1469 const char **thread_id)
1471 GHashTable *parents = NULL;
1472 const char *refs, *in_reply_to, *in_reply_to_message_id;
1473 GList *l, *keys = NULL;
1474 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1476 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1477 _my_talloc_free_for_g_hash, NULL);
1479 refs = notmuch_message_file_get_header (message_file, "references");
1480 parse_references (message, notmuch_message_get_message_id (message),
1483 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1484 parse_references (message, notmuch_message_get_message_id (message),
1485 parents, in_reply_to);
1487 /* Carefully avoid adding any self-referential in-reply-to term. */
1488 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1489 if (in_reply_to_message_id &&
1490 strcmp (in_reply_to_message_id,
1491 notmuch_message_get_message_id (message)))
1493 _notmuch_message_add_term (message, "replyto",
1494 _parse_message_id (message, in_reply_to, NULL));
1497 keys = g_hash_table_get_keys (parents);
1498 for (l = keys; l; l = l->next) {
1499 char *parent_message_id;
1500 const char *parent_thread_id = NULL;
1502 parent_message_id = (char *) l->data;
1504 _notmuch_message_add_term (message, "reference",
1507 ret = _resolve_message_id_to_thread_id (notmuch,
1514 if (*thread_id == NULL) {
1515 *thread_id = talloc_strdup (message, parent_thread_id);
1516 _notmuch_message_add_term (message, "thread", *thread_id);
1517 } else if (strcmp (*thread_id, parent_thread_id)) {
1518 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1528 g_hash_table_unref (parents);
1533 static notmuch_status_t
1534 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1535 notmuch_message_t *message,
1536 const char **thread_id)
1538 const char *message_id = notmuch_message_get_message_id (message);
1539 Xapian::PostingIterator child, children_end;
1540 notmuch_message_t *child_message = NULL;
1541 const char *child_thread_id;
1542 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1543 notmuch_private_status_t private_status;
1545 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1547 for ( ; child != children_end; child++) {
1549 child_message = _notmuch_message_create (message, notmuch,
1550 *child, &private_status);
1551 if (child_message == NULL) {
1552 ret = COERCE_STATUS (private_status,
1553 "Cannot find document for doc_id from query");
1557 child_thread_id = notmuch_message_get_thread_id (child_message);
1558 if (*thread_id == NULL) {
1559 *thread_id = talloc_strdup (message, child_thread_id);
1560 _notmuch_message_add_term (message, "thread", *thread_id);
1561 } else if (strcmp (*thread_id, child_thread_id)) {
1562 _notmuch_message_remove_term (child_message, "reference",
1564 _notmuch_message_sync (child_message);
1565 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1570 notmuch_message_destroy (child_message);
1571 child_message = NULL;
1576 notmuch_message_destroy (child_message);
1581 /* Given a (mostly empty) 'message' and its corresponding
1582 * 'message_file' link it to existing threads in the database.
1584 * The first check is in the metadata of the database to see if we
1585 * have pre-allocated a thread_id in advance for this message, (which
1586 * would have happened if a message was previously added that
1587 * referenced this one).
1589 * Second, we look at 'message_file' and its link-relevant headers
1590 * (References and In-Reply-To) for message IDs.
1592 * Finally, we look in the database for existing message that
1593 * reference 'message'.
1595 * In all cases, we assign to the current message the first thread_id
1596 * found (through either parent or child). We will also merge any
1597 * existing, distinct threads where this message belongs to both,
1598 * (which is not uncommon when messages are processed out of order).
1600 * Finally, if no thread ID has been found through parent or child, we
1601 * call _notmuch_message_generate_thread_id to generate a new thread
1602 * ID. This should only happen for new, top-level messages, (no
1603 * References or In-Reply-To header in this message, and no previously
1604 * added message refers to this message).
1606 static notmuch_status_t
1607 _notmuch_database_link_message (notmuch_database_t *notmuch,
1608 notmuch_message_t *message,
1609 notmuch_message_file_t *message_file)
1611 notmuch_status_t status;
1612 const char *message_id, *thread_id = NULL;
1616 message_id = notmuch_message_get_message_id (message);
1617 metadata_key = _get_metadata_thread_id_key (message, message_id);
1619 /* Check if we have already seen related messages to this one.
1620 * If we have then use the thread_id that we stored at that time.
1622 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1623 if (! stored_id.empty()) {
1624 Xapian::WritableDatabase *db;
1626 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1628 /* Clear the metadata for this message ID. We don't need it
1630 db->set_metadata (metadata_key, "");
1631 thread_id = stored_id.c_str();
1633 _notmuch_message_add_term (message, "thread", thread_id);
1635 talloc_free (metadata_key);
1637 status = _notmuch_database_link_message_to_parents (notmuch, message,
1643 status = _notmuch_database_link_message_to_children (notmuch, message,
1648 /* If not part of any existing thread, generate a new thread ID. */
1649 if (thread_id == NULL) {
1650 thread_id = _notmuch_database_generate_thread_id (notmuch);
1652 _notmuch_message_add_term (message, "thread", thread_id);
1655 return NOTMUCH_STATUS_SUCCESS;
1659 notmuch_database_add_message (notmuch_database_t *notmuch,
1660 const char *filename,
1661 notmuch_message_t **message_ret)
1663 notmuch_message_file_t *message_file;
1664 notmuch_message_t *message = NULL;
1665 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1666 notmuch_private_status_t private_status;
1668 const char *date, *header;
1669 const char *from, *to, *subject;
1670 char *message_id = NULL;
1673 *message_ret = NULL;
1675 ret = _notmuch_database_ensure_writable (notmuch);
1679 message_file = notmuch_message_file_open (filename);
1680 if (message_file == NULL)
1681 return NOTMUCH_STATUS_FILE_ERROR;
1683 /* Adding a message may change many documents. Do this all
1685 ret = notmuch_database_begin_atomic (notmuch);
1689 notmuch_message_file_restrict_headers (message_file,
1700 /* Before we do any real work, (especially before doing a
1701 * potential SHA-1 computation on the entire file's contents),
1702 * let's make sure that what we're looking at looks like an
1703 * actual email message.
1705 from = notmuch_message_file_get_header (message_file, "from");
1706 subject = notmuch_message_file_get_header (message_file, "subject");
1707 to = notmuch_message_file_get_header (message_file, "to");
1709 if ((from == NULL || *from == '\0') &&
1710 (subject == NULL || *subject == '\0') &&
1711 (to == NULL || *to == '\0'))
1713 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1717 /* Now that we're sure it's mail, the first order of business
1718 * is to find a message ID (or else create one ourselves). */
1720 header = notmuch_message_file_get_header (message_file, "message-id");
1721 if (header && *header != '\0') {
1722 message_id = _parse_message_id (message_file, header, NULL);
1724 /* So the header value isn't RFC-compliant, but it's
1725 * better than no message-id at all. */
1726 if (message_id == NULL)
1727 message_id = talloc_strdup (message_file, header);
1729 /* If a message ID is too long, substitute its sha1 instead. */
1730 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1731 char *compressed = _message_id_compressed (message_file,
1733 talloc_free (message_id);
1734 message_id = compressed;
1738 if (message_id == NULL ) {
1739 /* No message-id at all, let's generate one by taking a
1740 * hash over the file's contents. */
1741 char *sha1 = notmuch_sha1_of_file (filename);
1743 /* If that failed too, something is really wrong. Give up. */
1745 ret = NOTMUCH_STATUS_FILE_ERROR;
1749 message_id = talloc_asprintf (message_file,
1750 "notmuch-sha1-%s", sha1);
1754 /* Now that we have a message ID, we get a message object,
1755 * (which may or may not reference an existing document in the
1758 message = _notmuch_message_create_for_message_id (notmuch,
1762 talloc_free (message_id);
1764 if (message == NULL) {
1765 ret = COERCE_STATUS (private_status,
1766 "Unexpected status value from _notmuch_message_create_for_message_id");
1770 _notmuch_message_add_filename (message, filename);
1772 /* Is this a newly created message object? */
1773 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1774 _notmuch_message_add_term (message, "type", "mail");
1776 ret = _notmuch_database_link_message (notmuch, message,
1781 date = notmuch_message_file_get_header (message_file, "date");
1782 _notmuch_message_set_header_values (message, date, from, subject);
1784 _notmuch_message_index_file (message, filename);
1786 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1789 _notmuch_message_sync (message);
1790 } catch (const Xapian::Error &error) {
1791 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1792 error.get_msg().c_str());
1793 notmuch->exception_reported = TRUE;
1794 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1800 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1801 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1802 *message_ret = message;
1804 notmuch_message_destroy (message);
1808 notmuch_message_file_close (message_file);
1810 ret2 = notmuch_database_end_atomic (notmuch);
1811 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1812 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
1813 ret2 != NOTMUCH_STATUS_SUCCESS)
1820 notmuch_database_remove_message (notmuch_database_t *notmuch,
1821 const char *filename)
1823 notmuch_status_t status;
1824 notmuch_message_t *message;
1826 status = notmuch_database_find_message_by_filename (notmuch, filename,
1829 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1830 status = _notmuch_message_remove_filename (message, filename);
1831 if (status == NOTMUCH_STATUS_SUCCESS)
1832 _notmuch_message_delete (message);
1833 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1834 _notmuch_message_sync (message);
1836 notmuch_message_destroy (message);
1843 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1844 const char *filename,
1845 notmuch_message_t **message_ret)
1848 const char *prefix = _find_prefix ("file-direntry");
1849 char *direntry, *term;
1850 Xapian::PostingIterator i, end;
1851 notmuch_status_t status;
1853 if (message_ret == NULL)
1854 return NOTMUCH_STATUS_NULL_POINTER;
1856 /* return NULL on any failure */
1857 *message_ret = NULL;
1859 local = talloc_new (notmuch);
1862 status = _notmuch_database_filename_to_direntry (local, notmuch,
1863 filename, &direntry);
1867 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1869 find_doc_ids_for_term (notmuch, term, &i, &end);
1872 notmuch_private_status_t private_status;
1874 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1876 if (*message_ret == NULL)
1877 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1879 } catch (const Xapian::Error &error) {
1880 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
1881 error.get_msg().c_str());
1882 notmuch->exception_reported = TRUE;
1883 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1887 talloc_free (local);
1889 if (status && *message_ret) {
1890 notmuch_message_destroy (*message_ret);
1891 *message_ret = NULL;
1896 notmuch_string_list_t *
1897 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1898 Xapian::TermIterator &end,
1901 int prefix_len = strlen (prefix);
1902 notmuch_string_list_t *list;
1904 list = _notmuch_string_list_create (ctx);
1905 if (unlikely (list == NULL))
1908 for (i.skip_to (prefix); i != end; i++) {
1909 /* Terminate loop at first term without desired prefix. */
1910 if (strncmp ((*i).c_str (), prefix, prefix_len))
1913 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1920 notmuch_database_get_all_tags (notmuch_database_t *db)
1922 Xapian::TermIterator i, end;
1923 notmuch_string_list_t *tags;
1926 i = db->xapian_db->allterms_begin();
1927 end = db->xapian_db->allterms_end();
1928 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1929 _find_prefix ("tag"));
1930 _notmuch_string_list_sort (tags);
1931 return _notmuch_tags_create (db, tags);
1932 } catch (const Xapian::Error &error) {
1933 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1934 error.get_msg().c_str());
1935 db->exception_reported = TRUE;