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 */
33 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
40 #define NOTMUCH_DATABASE_VERSION 1
42 #define STRINGIFY(s) _SUB_STRINGIFY(s)
43 #define _SUB_STRINGIFY(s) #s
45 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
47 * We currently have two different types of documents (mail and
48 * directory) and also some metadata.
52 * A mail document is associated with a particular email message file
53 * on disk. It is indexed with the following prefixed terms which the
54 * database uses to construct threads, etc.:
56 * Single terms of given prefix:
60 * id: Unique ID of mail. This is from the Message-ID header
61 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
62 * If it's present and too long, then we use
63 * "notmuch-sha1-<sha1_sum_of_message_id>".
64 * If this header is not present, we use
65 * "notmuch-sha1-<sha1_sum_of_entire_file>".
67 * thread: The ID of the thread to which the mail belongs
69 * replyto: The ID from the In-Reply-To header of the mail (if any).
71 * Multiple terms of given prefix:
73 * reference: All message IDs from In-Reply-To and References
74 * headers in the message.
76 * tag: Any tags associated with this message by the user.
78 * file-direntry: A colon-separated pair of values
79 * (INTEGER:STRING), where INTEGER is the
80 * document ID of a directory document, and
81 * STRING is the name of a file within that
82 * directory for this mail message.
84 * A mail document also has four values:
86 * TIMESTAMP: The time_t value corresponding to the message's
89 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
91 * FROM: The value of the "From" header
93 * SUBJECT: The value of the "Subject" header
95 * In addition, terms from the content of the message are added with
96 * "from", "to", "attachment", and "subject" prefixes for use by the
97 * user in searching. Similarly, terms from the path of the mail
98 * message are added with a "folder" prefix. But the database doesn't
99 * really care itself about any of these.
101 * The data portion of a mail document is empty.
105 * A directory document is used by a client of the notmuch library to
106 * maintain data necessary to allow for efficient polling of mail
109 * All directory documents contain one term:
111 * directory: The directory path (relative to the database path)
112 * Or the SHA1 sum of the directory path (if the
113 * path itself is too long to fit in a Xapian
116 * And all directory documents for directories other than top-level
117 * directories also contain the following term:
119 * directory-direntry: A colon-separated pair of values
120 * (INTEGER:STRING), where INTEGER is the
121 * document ID of the parent directory
122 * document, and STRING is the name of this
123 * directory within that parent.
125 * All directory documents have a single value:
127 * TIMESTAMP: The mtime of the directory (at last scan)
129 * The data portion of a directory document contains the path of the
130 * directory (relative to the database path).
134 * Xapian allows us to store arbitrary name-value pairs as
135 * "metadata". We currently use the following metadata names with the
138 * version The database schema version, (which is distinct
139 * from both the notmuch package version (see
140 * notmuch --version) and the libnotmuch library
141 * version. The version is stored as an base-10
142 * ASCII integer. The initial database version
143 * was 1, (though a schema existed before that
144 * were no "version" database value existed at
145 * all). Successive versions are allocated as
146 * changes are made to the database (such as by
147 * indexing new fields).
149 * last_thread_id The last thread ID generated. This is stored
150 * as a 16-byte hexadecimal ASCII representation
151 * of a 64-bit unsigned integer. The first ID
152 * generated is 1 and the value will be
153 * incremented for each thread ID.
155 * thread_id_* A pre-allocated thread ID for a particular
156 * message. This is actually an arbitrarily large
157 * family of metadata name. Any particular name is
158 * formed by concatenating "thread_id_" with a message
159 * ID (or the SHA1 sum of a message ID if it is very
160 * long---see description of 'id' in the mail
161 * document). The value stored is a thread ID.
163 * These thread ID metadata values are stored
164 * whenever a message references a parent message
165 * that does not yet exist in the database. A
166 * thread ID will be allocated and stored, and if
167 * the message is later added, the stored thread
168 * ID will be used (and the metadata value will
171 * Even before a message is added, it's
172 * pre-allocated thread ID is useful so that all
173 * descendant messages that reference this common
174 * parent can be recognized as belonging to the
178 /* With these prefix values we follow the conventions published here:
180 * http://xapian.org/docs/omega/termprefixes.html
182 * as much as makes sense. Note that I took some liberty in matching
183 * the reserved prefix values to notmuch concepts, (for example, 'G'
184 * is documented as "newsGroup (or similar entity - e.g. a web forum
185 * name)", for which I think the thread is the closest analogue in
186 * notmuch. This in spite of the fact that we will eventually be
187 * storing mailing-list messages where 'G' for "mailing list name"
188 * might be even a closer analogue. I'm treating the single-character
189 * prefixes preferentially for core notmuch concepts (which will be
190 * nearly universal to all mail messages).
193 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
195 { "reference", "XREFERENCE" },
196 { "replyto", "XREPLYTO" },
197 { "directory", "XDIRECTORY" },
198 { "file-direntry", "XFDIRENTRY" },
199 { "directory-direntry", "XDDIRENTRY" },
202 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
209 static prefix_t PROBABILISTIC_PREFIX[]= {
212 { "attachment", "XATTACHMENT" },
213 { "subject", "XSUBJECT"},
214 { "folder", "XFOLDER"}
218 _find_prefix (const char *name)
222 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
223 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
224 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
227 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
228 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
229 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
232 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
233 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
234 return PROBABILISTIC_PREFIX[i].prefix;
237 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
243 notmuch_status_to_string (notmuch_status_t status)
246 case NOTMUCH_STATUS_SUCCESS:
247 return "No error occurred";
248 case NOTMUCH_STATUS_OUT_OF_MEMORY:
249 return "Out of memory";
250 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
251 return "Attempt to write to a read-only database";
252 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
253 return "A Xapian exception occurred";
254 case NOTMUCH_STATUS_FILE_ERROR:
255 return "Something went wrong trying to read or write a file";
256 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
257 return "File is not an email";
258 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
259 return "Message ID is identical to a message in database";
260 case NOTMUCH_STATUS_NULL_POINTER:
261 return "Erroneous NULL pointer";
262 case NOTMUCH_STATUS_TAG_TOO_LONG:
263 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
264 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
265 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
266 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
267 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
269 case NOTMUCH_STATUS_LAST_STATUS:
270 return "Unknown error status value";
275 find_doc_ids_for_term (notmuch_database_t *notmuch,
277 Xapian::PostingIterator *begin,
278 Xapian::PostingIterator *end)
280 *begin = notmuch->xapian_db->postlist_begin (term);
282 *end = notmuch->xapian_db->postlist_end (term);
286 find_doc_ids (notmuch_database_t *notmuch,
287 const char *prefix_name,
289 Xapian::PostingIterator *begin,
290 Xapian::PostingIterator *end)
294 term = talloc_asprintf (notmuch, "%s%s",
295 _find_prefix (prefix_name), value);
297 find_doc_ids_for_term (notmuch, term, begin, end);
302 notmuch_private_status_t
303 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
304 const char *prefix_name,
306 unsigned int *doc_id)
308 Xapian::PostingIterator i, end;
310 find_doc_ids (notmuch, prefix_name, value, &i, &end);
314 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
319 #if DEBUG_DATABASE_SANITY
323 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
327 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
330 static Xapian::Document
331 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
333 return notmuch->xapian_db->get_document (doc_id);
336 /* Generate a compressed version of 'message_id' of the form:
338 * notmuch-sha1-<sha1_sum_of_message_id>
341 _message_id_compressed (void *ctx, const char *message_id)
343 char *sha1, *compressed;
345 sha1 = notmuch_sha1_of_string (message_id);
347 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
354 notmuch_database_find_message (notmuch_database_t *notmuch,
355 const char *message_id,
356 notmuch_message_t **message_ret)
358 notmuch_private_status_t status;
361 if (message_ret == NULL)
362 return NOTMUCH_STATUS_NULL_POINTER;
364 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
365 message_id = _message_id_compressed (notmuch, message_id);
368 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
369 message_id, &doc_id);
371 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
374 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
376 if (*message_ret == NULL)
377 return NOTMUCH_STATUS_OUT_OF_MEMORY;
380 return NOTMUCH_STATUS_SUCCESS;
381 } catch (const Xapian::Error &error) {
382 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
383 error.get_msg().c_str());
384 notmuch->exception_reported = TRUE;
386 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
390 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
391 * a (potentially nested) parenthesized sequence with '\' used to
392 * escape any character (including parentheses).
394 * If the sequence to be skipped continues to the end of the string,
395 * then 'str' will be left pointing at the final terminating '\0'
399 skip_space_and_comments (const char **str)
404 while (*s && (isspace (*s) || *s == '(')) {
405 while (*s && isspace (*s))
410 while (*s && nesting) {
413 } else if (*s == ')') {
415 } else if (*s == '\\') {
427 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
428 * comments, and the '<' and '>' delimiters.
430 * If not NULL, then *next will be made to point to the first character
431 * not parsed, (possibly pointing to the final '\0' terminator.
433 * Returns a newly talloc'ed string belonging to 'ctx'.
435 * Returns NULL if there is any error parsing the message-id. */
437 _parse_message_id (void *ctx, const char *message_id, const char **next)
442 if (message_id == NULL || *message_id == '\0')
447 skip_space_and_comments (&s);
449 /* Skip any unstructured text as well. */
450 while (*s && *s != '<')
461 skip_space_and_comments (&s);
464 while (*end && *end != '>')
473 if (end > s && *end == '>')
478 result = talloc_strndup (ctx, s, end - s + 1);
480 /* Finally, collapse any whitespace that is within the message-id
486 for (r = result, len = strlen (r); *r; r++, len--)
487 if (*r == ' ' || *r == '\t')
488 memmove (r, r+1, len);
494 /* Parse a References header value, putting a (talloc'ed under 'ctx')
495 * copy of each referenced message-id into 'hash'.
497 * We explicitly avoid including any reference identical to
498 * 'message_id' in the result (to avoid mass confusion when a single
499 * message references itself cyclically---and yes, mail messages are
500 * not infrequent in the wild that do this---don't ask me why).
503 parse_references (void *ctx,
504 const char *message_id,
510 if (refs == NULL || *refs == '\0')
514 ref = _parse_message_id (ctx, refs, &refs);
516 if (ref && strcmp (ref, message_id))
517 g_hash_table_insert (hash, ref, NULL);
522 notmuch_database_create (const char *path)
524 notmuch_database_t *notmuch = NULL;
525 char *notmuch_path = NULL;
530 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
534 err = stat (path, &st);
536 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
537 path, strerror (errno));
541 if (! S_ISDIR (st.st_mode)) {
542 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
547 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
549 err = mkdir (notmuch_path, 0755);
552 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
553 notmuch_path, strerror (errno));
557 notmuch = notmuch_database_open (path,
558 NOTMUCH_DATABASE_MODE_READ_WRITE);
559 notmuch_database_upgrade (notmuch, NULL, NULL);
563 talloc_free (notmuch_path);
569 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
571 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
572 fprintf (stderr, "Cannot write to a read-only database.\n");
573 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
576 return NOTMUCH_STATUS_SUCCESS;
580 notmuch_database_open (const char *path,
581 notmuch_database_mode_t mode)
583 notmuch_database_t *notmuch = NULL;
584 char *notmuch_path = NULL, *xapian_path = NULL;
587 unsigned int i, version;
589 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
591 fprintf (stderr, "Out of memory\n");
595 err = stat (notmuch_path, &st);
597 fprintf (stderr, "Error opening database at %s: %s\n",
598 notmuch_path, strerror (errno));
602 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
604 fprintf (stderr, "Out of memory\n");
608 /* Initialize the GLib type system and threads */
611 notmuch = talloc (NULL, notmuch_database_t);
612 notmuch->exception_reported = FALSE;
613 notmuch->path = talloc_strdup (notmuch, path);
615 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
616 notmuch->path[strlen (notmuch->path) - 1] = '\0';
618 notmuch->needs_upgrade = FALSE;
619 notmuch->mode = mode;
620 notmuch->atomic_nesting = 0;
622 string last_thread_id;
624 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
625 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
626 Xapian::DB_CREATE_OR_OPEN);
627 version = notmuch_database_get_version (notmuch);
629 if (version > NOTMUCH_DATABASE_VERSION) {
631 "Error: Notmuch database at %s\n"
632 " has a newer database format version (%u) than supported by this\n"
633 " version of notmuch (%u). Refusing to open this database in\n"
634 " read-write mode.\n",
635 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
636 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
637 notmuch_database_close (notmuch);
642 if (version < NOTMUCH_DATABASE_VERSION)
643 notmuch->needs_upgrade = TRUE;
645 notmuch->xapian_db = new Xapian::Database (xapian_path);
646 version = notmuch_database_get_version (notmuch);
647 if (version > NOTMUCH_DATABASE_VERSION)
650 "Warning: Notmuch database at %s\n"
651 " has a newer database format version (%u) than supported by this\n"
652 " version of notmuch (%u). Some operations may behave incorrectly,\n"
653 " (but the database will not be harmed since it is being opened\n"
654 " in read-only mode).\n",
655 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
659 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
660 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
661 if (last_thread_id.empty ()) {
662 notmuch->last_thread_id = 0;
667 str = last_thread_id.c_str ();
668 notmuch->last_thread_id = strtoull (str, &end, 16);
670 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
673 notmuch->query_parser = new Xapian::QueryParser;
674 notmuch->term_gen = new Xapian::TermGenerator;
675 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
676 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
678 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
679 notmuch->query_parser->set_database (*notmuch->xapian_db);
680 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
681 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
682 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
684 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
685 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
686 notmuch->query_parser->add_boolean_prefix (prefix->name,
690 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
691 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
692 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
694 } catch (const Xapian::Error &error) {
695 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
696 error.get_msg().c_str());
710 notmuch_database_close (notmuch_database_t *notmuch)
713 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
714 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
715 } catch (const Xapian::Error &error) {
716 if (! notmuch->exception_reported) {
717 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
718 error.get_msg().c_str());
722 delete notmuch->term_gen;
723 delete notmuch->query_parser;
724 delete notmuch->xapian_db;
725 delete notmuch->value_range_processor;
726 talloc_free (notmuch);
730 notmuch_database_get_path (notmuch_database_t *notmuch)
732 return notmuch->path;
736 notmuch_database_get_version (notmuch_database_t *notmuch)
738 unsigned int version;
739 string version_string;
743 version_string = notmuch->xapian_db->get_metadata ("version");
744 if (version_string.empty ())
747 str = version_string.c_str ();
748 if (str == NULL || *str == '\0')
751 version = strtoul (str, &end, 10);
753 INTERNAL_ERROR ("Malformed database version: %s", str);
759 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
761 return notmuch->needs_upgrade;
764 static volatile sig_atomic_t do_progress_notify = 0;
767 handle_sigalrm (unused (int signal))
769 do_progress_notify = 1;
772 /* Upgrade the current database.
774 * After opening a database in read-write mode, the client should
775 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
776 * if so, upgrade with this function before making any modifications.
778 * The optional progress_notify callback can be used by the caller to
779 * provide progress indication to the user. If non-NULL it will be
780 * called periodically with 'count' as the number of messages upgraded
781 * so far and 'total' the overall number of messages that will be
785 notmuch_database_upgrade (notmuch_database_t *notmuch,
786 void (*progress_notify) (void *closure,
790 Xapian::WritableDatabase *db;
791 struct sigaction action;
792 struct itimerval timerval;
793 notmuch_bool_t timer_is_active = FALSE;
794 unsigned int version;
795 notmuch_status_t status;
796 unsigned int count = 0, total = 0;
798 status = _notmuch_database_ensure_writable (notmuch);
802 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
804 version = notmuch_database_get_version (notmuch);
806 if (version >= NOTMUCH_DATABASE_VERSION)
807 return NOTMUCH_STATUS_SUCCESS;
809 if (progress_notify) {
810 /* Setup our handler for SIGALRM */
811 memset (&action, 0, sizeof (struct sigaction));
812 action.sa_handler = handle_sigalrm;
813 sigemptyset (&action.sa_mask);
814 action.sa_flags = SA_RESTART;
815 sigaction (SIGALRM, &action, NULL);
817 /* Then start a timer to send SIGALRM once per second. */
818 timerval.it_interval.tv_sec = 1;
819 timerval.it_interval.tv_usec = 0;
820 timerval.it_value.tv_sec = 1;
821 timerval.it_value.tv_usec = 0;
822 setitimer (ITIMER_REAL, &timerval, NULL);
824 timer_is_active = TRUE;
827 /* Before version 1, each message document had its filename in the
828 * data field. Copy that into the new format by calling
829 * notmuch_message_add_filename.
832 notmuch_query_t *query = notmuch_query_create (notmuch, "");
833 notmuch_messages_t *messages;
834 notmuch_message_t *message;
836 Xapian::TermIterator t, t_end;
838 total = notmuch_query_count_messages (query);
840 for (messages = notmuch_query_search_messages (query);
841 notmuch_messages_valid (messages);
842 notmuch_messages_move_to_next (messages))
844 if (do_progress_notify) {
845 progress_notify (closure, (double) count / total);
846 do_progress_notify = 0;
849 message = notmuch_messages_get (messages);
851 filename = _notmuch_message_talloc_copy_data (message);
852 if (filename && *filename != '\0') {
853 _notmuch_message_add_filename (message, filename);
854 _notmuch_message_sync (message);
856 talloc_free (filename);
858 notmuch_message_destroy (message);
863 notmuch_query_destroy (query);
865 /* Also, before version 1 we stored directory timestamps in
866 * XTIMESTAMP documents instead of the current XDIRECTORY
867 * documents. So copy those as well. */
869 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
871 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
875 Xapian::PostingIterator p, p_end;
876 std::string term = *t;
878 p_end = notmuch->xapian_db->postlist_end (term);
880 for (p = notmuch->xapian_db->postlist_begin (term);
884 Xapian::Document document;
886 notmuch_directory_t *directory;
888 if (do_progress_notify) {
889 progress_notify (closure, (double) count / total);
890 do_progress_notify = 0;
893 document = find_document_for_doc_id (notmuch, *p);
894 mtime = Xapian::sortable_unserialise (
895 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
897 directory = notmuch_database_get_directory (notmuch,
899 notmuch_directory_set_mtime (directory, mtime);
900 notmuch_directory_destroy (directory);
905 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
908 /* Now that the upgrade is complete we can remove the old data
909 * and documents that are no longer needed. */
911 notmuch_query_t *query = notmuch_query_create (notmuch, "");
912 notmuch_messages_t *messages;
913 notmuch_message_t *message;
916 for (messages = notmuch_query_search_messages (query);
917 notmuch_messages_valid (messages);
918 notmuch_messages_move_to_next (messages))
920 if (do_progress_notify) {
921 progress_notify (closure, (double) count / total);
922 do_progress_notify = 0;
925 message = notmuch_messages_get (messages);
927 filename = _notmuch_message_talloc_copy_data (message);
928 if (filename && *filename != '\0') {
929 _notmuch_message_clear_data (message);
930 _notmuch_message_sync (message);
932 talloc_free (filename);
934 notmuch_message_destroy (message);
937 notmuch_query_destroy (query);
941 Xapian::TermIterator t, t_end;
943 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
945 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
949 Xapian::PostingIterator p, p_end;
950 std::string term = *t;
952 p_end = notmuch->xapian_db->postlist_end (term);
954 for (p = notmuch->xapian_db->postlist_begin (term);
958 if (do_progress_notify) {
959 progress_notify (closure, (double) count / total);
960 do_progress_notify = 0;
963 db->delete_document (*p);
968 if (timer_is_active) {
969 /* Now stop the timer. */
970 timerval.it_interval.tv_sec = 0;
971 timerval.it_interval.tv_usec = 0;
972 timerval.it_value.tv_sec = 0;
973 timerval.it_value.tv_usec = 0;
974 setitimer (ITIMER_REAL, &timerval, NULL);
976 /* And disable the signal handler. */
977 action.sa_handler = SIG_IGN;
978 sigaction (SIGALRM, &action, NULL);
981 return NOTMUCH_STATUS_SUCCESS;
985 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
987 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
988 notmuch->atomic_nesting > 0)
992 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
993 } catch (const Xapian::Error &error) {
994 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
995 error.get_msg().c_str());
996 notmuch->exception_reported = TRUE;
997 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1001 notmuch->atomic_nesting++;
1002 return NOTMUCH_STATUS_SUCCESS;
1006 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1008 Xapian::WritableDatabase *db;
1010 if (notmuch->atomic_nesting == 0)
1011 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1013 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1014 notmuch->atomic_nesting > 1)
1017 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1019 db->commit_transaction ();
1021 /* This is a hack for testing. Xapian never flushes on a
1022 * non-flushed commit, even if the flush threshold is 1.
1023 * However, we rely on flushing to test atomicity. */
1024 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1025 if (thresh && atoi (thresh) == 1)
1027 } catch (const Xapian::Error &error) {
1028 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1029 error.get_msg().c_str());
1030 notmuch->exception_reported = TRUE;
1031 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1035 notmuch->atomic_nesting--;
1036 return NOTMUCH_STATUS_SUCCESS;
1039 /* We allow the user to use arbitrarily long paths for directories. But
1040 * we have a term-length limit. So if we exceed that, we'll use the
1041 * SHA-1 of the path for the database term.
1043 * Note: This function may return the original value of 'path'. If it
1044 * does not, then the caller is responsible to free() the returned
1048 _notmuch_database_get_directory_db_path (const char *path)
1050 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1052 if (term_len > NOTMUCH_TERM_MAX)
1053 return notmuch_sha1_of_string (path);
1058 /* Given a path, split it into two parts: the directory part is all
1059 * components except for the last, and the basename is that last
1060 * component. Getting the return-value for either part is optional
1061 * (the caller can pass NULL).
1063 * The original 'path' can represent either a regular file or a
1064 * directory---the splitting will be carried out in the same way in
1065 * either case. Trailing slashes on 'path' will be ignored, and any
1066 * cases of multiple '/' characters appearing in series will be
1067 * treated as a single '/'.
1069 * Allocation (if any) will have 'ctx' as the talloc owner. But
1070 * pointers will be returned within the original path string whenever
1073 * Note: If 'path' is non-empty and contains no non-trailing slash,
1074 * (that is, consists of a filename with no parent directory), then
1075 * the directory returned will be an empty string. However, if 'path'
1076 * is an empty string, then both directory and basename will be
1080 _notmuch_database_split_path (void *ctx,
1082 const char **directory,
1083 const char **basename)
1087 if (path == NULL || *path == '\0') {
1092 return NOTMUCH_STATUS_SUCCESS;
1095 /* Find the last slash (not counting a trailing slash), if any. */
1097 slash = path + strlen (path) - 1;
1099 /* First, skip trailing slashes. */
1100 while (slash != path) {
1107 /* Then, find a slash. */
1108 while (slash != path) {
1118 /* Finally, skip multiple slashes. */
1119 while (slash != path) {
1126 if (slash == path) {
1128 *directory = talloc_strdup (ctx, "");
1133 *directory = talloc_strndup (ctx, path, slash - path + 1);
1136 return NOTMUCH_STATUS_SUCCESS;
1140 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1142 unsigned int *directory_id)
1144 notmuch_directory_t *directory;
1145 notmuch_status_t status;
1149 return NOTMUCH_STATUS_SUCCESS;
1152 directory = _notmuch_directory_create (notmuch, path, &status);
1158 *directory_id = _notmuch_directory_get_document_id (directory);
1160 notmuch_directory_destroy (directory);
1162 return NOTMUCH_STATUS_SUCCESS;
1166 _notmuch_database_get_directory_path (void *ctx,
1167 notmuch_database_t *notmuch,
1168 unsigned int doc_id)
1170 Xapian::Document document;
1172 document = find_document_for_doc_id (notmuch, doc_id);
1174 return talloc_strdup (ctx, document.get_data ().c_str ());
1177 /* Given a legal 'filename' for the database, (either relative to
1178 * database path or absolute with initial components identical to
1179 * database path), return a new string (with 'ctx' as the talloc
1180 * owner) suitable for use as a direntry term value.
1182 * The necessary directory documents will be created in the database
1186 _notmuch_database_filename_to_direntry (void *ctx,
1187 notmuch_database_t *notmuch,
1188 const char *filename,
1191 const char *relative, *directory, *basename;
1192 Xapian::docid directory_id;
1193 notmuch_status_t status;
1195 relative = _notmuch_database_relative_path (notmuch, filename);
1197 status = _notmuch_database_split_path (ctx, relative,
1198 &directory, &basename);
1202 status = _notmuch_database_find_directory_id (notmuch, directory,
1207 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1209 return NOTMUCH_STATUS_SUCCESS;
1212 /* Given a legal 'path' for the database, return the relative path.
1214 * The return value will be a pointer to the original path contents,
1215 * and will be either the original string (if 'path' was relative) or
1216 * a portion of the string (if path was absolute and begins with the
1220 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1223 const char *db_path, *relative;
1224 unsigned int db_path_len;
1226 db_path = notmuch_database_get_path (notmuch);
1227 db_path_len = strlen (db_path);
1231 if (*relative == '/') {
1232 while (*relative == '/' && *(relative+1) == '/')
1235 if (strncmp (relative, db_path, db_path_len) == 0)
1237 relative += db_path_len;
1238 while (*relative == '/')
1246 notmuch_directory_t *
1247 notmuch_database_get_directory (notmuch_database_t *notmuch,
1250 notmuch_status_t status;
1253 return _notmuch_directory_create (notmuch, path, &status);
1254 } catch (const Xapian::Error &error) {
1255 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1256 error.get_msg().c_str());
1257 notmuch->exception_reported = TRUE;
1262 /* Allocate a document ID that satisfies the following criteria:
1264 * 1. The ID does not exist for any document in the Xapian database
1266 * 2. The ID was not previously returned from this function
1268 * 3. The ID is the smallest integer satisfying (1) and (2)
1270 * This function will trigger an internal error if these constraints
1271 * cannot all be satisfied, (that is, the pool of available document
1272 * IDs has been exhausted).
1275 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1277 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1279 notmuch->last_doc_id++;
1281 if (notmuch->last_doc_id == 0)
1282 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1284 return notmuch->last_doc_id;
1288 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1290 /* 16 bytes (+ terminator) for hexadecimal representation of
1291 * a 64-bit integer. */
1292 static char thread_id[17];
1293 Xapian::WritableDatabase *db;
1295 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1297 notmuch->last_thread_id++;
1299 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1301 db->set_metadata ("last_thread_id", thread_id);
1307 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1309 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1310 message_id = _message_id_compressed (ctx, message_id);
1312 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1316 /* Find the thread ID to which the message with 'message_id' belongs.
1318 * Note: 'thread_id_ret' must not be NULL!
1319 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1322 * Note: If there is no message in the database with the given
1323 * 'message_id' then a new thread_id will be allocated for this
1324 * message and stored in the database metadata, (where this same
1325 * thread ID can be looked up if the message is added to the database
1328 static notmuch_status_t
1329 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1331 const char *message_id,
1332 const char **thread_id_ret)
1334 notmuch_status_t status;
1335 notmuch_message_t *message;
1336 string thread_id_string;
1338 Xapian::WritableDatabase *db;
1340 status = notmuch_database_find_message (notmuch, message_id, &message);
1346 *thread_id_ret = talloc_steal (ctx,
1347 notmuch_message_get_thread_id (message));
1349 notmuch_message_destroy (message);
1351 return NOTMUCH_STATUS_SUCCESS;
1354 /* Message has not been seen yet.
1356 * We may have seen a reference to it already, in which case, we
1357 * can return the thread ID stored in the metadata. Otherwise, we
1358 * generate a new thread ID and store it there.
1360 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1361 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1362 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1364 if (thread_id_string.empty()) {
1365 *thread_id_ret = talloc_strdup (ctx,
1366 _notmuch_database_generate_thread_id (notmuch));
1367 db->set_metadata (metadata_key, *thread_id_ret);
1369 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1372 talloc_free (metadata_key);
1374 return NOTMUCH_STATUS_SUCCESS;
1377 static notmuch_status_t
1378 _merge_threads (notmuch_database_t *notmuch,
1379 const char *winner_thread_id,
1380 const char *loser_thread_id)
1382 Xapian::PostingIterator loser, loser_end;
1383 notmuch_message_t *message = NULL;
1384 notmuch_private_status_t private_status;
1385 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1387 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1389 for ( ; loser != loser_end; loser++) {
1390 message = _notmuch_message_create (notmuch, notmuch,
1391 *loser, &private_status);
1392 if (message == NULL) {
1393 ret = COERCE_STATUS (private_status,
1394 "Cannot find document for doc_id from query");
1398 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1399 _notmuch_message_add_term (message, "thread", winner_thread_id);
1400 _notmuch_message_sync (message);
1402 notmuch_message_destroy (message);
1408 notmuch_message_destroy (message);
1414 _my_talloc_free_for_g_hash (void *ptr)
1419 static notmuch_status_t
1420 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1421 notmuch_message_t *message,
1422 notmuch_message_file_t *message_file,
1423 const char **thread_id)
1425 GHashTable *parents = NULL;
1426 const char *refs, *in_reply_to, *in_reply_to_message_id;
1427 GList *l, *keys = NULL;
1428 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1430 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1431 _my_talloc_free_for_g_hash, NULL);
1433 refs = notmuch_message_file_get_header (message_file, "references");
1434 parse_references (message, notmuch_message_get_message_id (message),
1437 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1438 parse_references (message, notmuch_message_get_message_id (message),
1439 parents, in_reply_to);
1441 /* Carefully avoid adding any self-referential in-reply-to term. */
1442 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1443 if (in_reply_to_message_id &&
1444 strcmp (in_reply_to_message_id,
1445 notmuch_message_get_message_id (message)))
1447 _notmuch_message_add_term (message, "replyto",
1448 _parse_message_id (message, in_reply_to, NULL));
1451 keys = g_hash_table_get_keys (parents);
1452 for (l = keys; l; l = l->next) {
1453 char *parent_message_id;
1454 const char *parent_thread_id = NULL;
1456 parent_message_id = (char *) l->data;
1458 _notmuch_message_add_term (message, "reference",
1461 ret = _resolve_message_id_to_thread_id (notmuch,
1468 if (*thread_id == NULL) {
1469 *thread_id = talloc_strdup (message, parent_thread_id);
1470 _notmuch_message_add_term (message, "thread", *thread_id);
1471 } else if (strcmp (*thread_id, parent_thread_id)) {
1472 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1482 g_hash_table_unref (parents);
1487 static notmuch_status_t
1488 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1489 notmuch_message_t *message,
1490 const char **thread_id)
1492 const char *message_id = notmuch_message_get_message_id (message);
1493 Xapian::PostingIterator child, children_end;
1494 notmuch_message_t *child_message = NULL;
1495 const char *child_thread_id;
1496 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1497 notmuch_private_status_t private_status;
1499 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1501 for ( ; child != children_end; child++) {
1503 child_message = _notmuch_message_create (message, notmuch,
1504 *child, &private_status);
1505 if (child_message == NULL) {
1506 ret = COERCE_STATUS (private_status,
1507 "Cannot find document for doc_id from query");
1511 child_thread_id = notmuch_message_get_thread_id (child_message);
1512 if (*thread_id == NULL) {
1513 *thread_id = talloc_strdup (message, child_thread_id);
1514 _notmuch_message_add_term (message, "thread", *thread_id);
1515 } else if (strcmp (*thread_id, child_thread_id)) {
1516 _notmuch_message_remove_term (child_message, "reference",
1518 _notmuch_message_sync (child_message);
1519 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1524 notmuch_message_destroy (child_message);
1525 child_message = NULL;
1530 notmuch_message_destroy (child_message);
1535 /* Given a (mostly empty) 'message' and its corresponding
1536 * 'message_file' link it to existing threads in the database.
1538 * The first check is in the metadata of the database to see if we
1539 * have pre-allocated a thread_id in advance for this message, (which
1540 * would have happened if a message was previously added that
1541 * referenced this one).
1543 * Second, we look at 'message_file' and its link-relevant headers
1544 * (References and In-Reply-To) for message IDs.
1546 * Finally, we look in the database for existing message that
1547 * reference 'message'.
1549 * In all cases, we assign to the current message the first thread_id
1550 * found (through either parent or child). We will also merge any
1551 * existing, distinct threads where this message belongs to both,
1552 * (which is not uncommon when messages are processed out of order).
1554 * Finally, if no thread ID has been found through parent or child, we
1555 * call _notmuch_message_generate_thread_id to generate a new thread
1556 * ID. This should only happen for new, top-level messages, (no
1557 * References or In-Reply-To header in this message, and no previously
1558 * added message refers to this message).
1560 static notmuch_status_t
1561 _notmuch_database_link_message (notmuch_database_t *notmuch,
1562 notmuch_message_t *message,
1563 notmuch_message_file_t *message_file)
1565 notmuch_status_t status;
1566 const char *message_id, *thread_id = NULL;
1570 message_id = notmuch_message_get_message_id (message);
1571 metadata_key = _get_metadata_thread_id_key (message, message_id);
1573 /* Check if we have already seen related messages to this one.
1574 * If we have then use the thread_id that we stored at that time.
1576 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1577 if (! stored_id.empty()) {
1578 Xapian::WritableDatabase *db;
1580 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1582 /* Clear the metadata for this message ID. We don't need it
1584 db->set_metadata (metadata_key, "");
1585 thread_id = stored_id.c_str();
1587 _notmuch_message_add_term (message, "thread", thread_id);
1589 talloc_free (metadata_key);
1591 status = _notmuch_database_link_message_to_parents (notmuch, message,
1597 status = _notmuch_database_link_message_to_children (notmuch, message,
1602 /* If not part of any existing thread, generate a new thread ID. */
1603 if (thread_id == NULL) {
1604 thread_id = _notmuch_database_generate_thread_id (notmuch);
1606 _notmuch_message_add_term (message, "thread", thread_id);
1609 return NOTMUCH_STATUS_SUCCESS;
1613 notmuch_database_add_message (notmuch_database_t *notmuch,
1614 const char *filename,
1615 notmuch_message_t **message_ret)
1617 notmuch_message_file_t *message_file;
1618 notmuch_message_t *message = NULL;
1619 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1620 notmuch_private_status_t private_status;
1622 const char *date, *header;
1623 const char *from, *to, *subject;
1624 char *message_id = NULL;
1627 *message_ret = NULL;
1629 ret = _notmuch_database_ensure_writable (notmuch);
1633 message_file = notmuch_message_file_open (filename);
1634 if (message_file == NULL)
1635 return NOTMUCH_STATUS_FILE_ERROR;
1637 /* Adding a message may change many documents. Do this all
1639 ret = notmuch_database_begin_atomic (notmuch);
1643 notmuch_message_file_restrict_headers (message_file,
1654 /* Before we do any real work, (especially before doing a
1655 * potential SHA-1 computation on the entire file's contents),
1656 * let's make sure that what we're looking at looks like an
1657 * actual email message.
1659 from = notmuch_message_file_get_header (message_file, "from");
1660 subject = notmuch_message_file_get_header (message_file, "subject");
1661 to = notmuch_message_file_get_header (message_file, "to");
1663 if ((from == NULL || *from == '\0') &&
1664 (subject == NULL || *subject == '\0') &&
1665 (to == NULL || *to == '\0'))
1667 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1671 /* Now that we're sure it's mail, the first order of business
1672 * is to find a message ID (or else create one ourselves). */
1674 header = notmuch_message_file_get_header (message_file, "message-id");
1675 if (header && *header != '\0') {
1676 message_id = _parse_message_id (message_file, header, NULL);
1678 /* So the header value isn't RFC-compliant, but it's
1679 * better than no message-id at all. */
1680 if (message_id == NULL)
1681 message_id = talloc_strdup (message_file, header);
1683 /* If a message ID is too long, substitute its sha1 instead. */
1684 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1685 char *compressed = _message_id_compressed (message_file,
1687 talloc_free (message_id);
1688 message_id = compressed;
1692 if (message_id == NULL ) {
1693 /* No message-id at all, let's generate one by taking a
1694 * hash over the file's contents. */
1695 char *sha1 = notmuch_sha1_of_file (filename);
1697 /* If that failed too, something is really wrong. Give up. */
1699 ret = NOTMUCH_STATUS_FILE_ERROR;
1703 message_id = talloc_asprintf (message_file,
1704 "notmuch-sha1-%s", sha1);
1708 /* Now that we have a message ID, we get a message object,
1709 * (which may or may not reference an existing document in the
1712 message = _notmuch_message_create_for_message_id (notmuch,
1716 talloc_free (message_id);
1718 if (message == NULL) {
1719 ret = COERCE_STATUS (private_status,
1720 "Unexpected status value from _notmuch_message_create_for_message_id");
1724 _notmuch_message_add_filename (message, filename);
1726 /* Is this a newly created message object? */
1727 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1728 _notmuch_message_add_term (message, "type", "mail");
1730 ret = _notmuch_database_link_message (notmuch, message,
1735 date = notmuch_message_file_get_header (message_file, "date");
1736 _notmuch_message_set_header_values (message, date, from, subject);
1738 _notmuch_message_index_file (message, filename);
1740 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1743 _notmuch_message_sync (message);
1744 } catch (const Xapian::Error &error) {
1745 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1746 error.get_msg().c_str());
1747 notmuch->exception_reported = TRUE;
1748 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1754 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1755 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1756 *message_ret = message;
1758 notmuch_message_destroy (message);
1762 notmuch_message_file_close (message_file);
1764 ret2 = notmuch_database_end_atomic (notmuch);
1765 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1766 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
1767 ret2 != NOTMUCH_STATUS_SUCCESS)
1774 notmuch_database_remove_message (notmuch_database_t *notmuch,
1775 const char *filename)
1777 notmuch_status_t status;
1778 notmuch_message_t *message;
1780 status = notmuch_database_find_message_by_filename (notmuch, filename,
1783 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1784 status = _notmuch_message_remove_filename (message, filename);
1785 if (status == NOTMUCH_STATUS_SUCCESS)
1786 _notmuch_message_delete (message);
1787 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1788 _notmuch_message_sync (message);
1790 notmuch_message_destroy (message);
1797 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1798 const char *filename,
1799 notmuch_message_t **message_ret)
1802 const char *prefix = _find_prefix ("file-direntry");
1803 char *direntry, *term;
1804 Xapian::PostingIterator i, end;
1805 notmuch_status_t status;
1807 if (message_ret == NULL)
1808 return NOTMUCH_STATUS_NULL_POINTER;
1810 local = talloc_new (notmuch);
1813 status = _notmuch_database_filename_to_direntry (local, notmuch,
1814 filename, &direntry);
1818 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1820 find_doc_ids_for_term (notmuch, term, &i, &end);
1823 notmuch_private_status_t private_status;
1825 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1827 if (*message_ret == NULL)
1828 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1830 } catch (const Xapian::Error &error) {
1831 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
1832 error.get_msg().c_str());
1833 notmuch->exception_reported = TRUE;
1834 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1838 talloc_free (local);
1840 if (status && *message_ret) {
1841 notmuch_message_destroy (*message_ret);
1842 *message_ret = NULL;
1847 notmuch_string_list_t *
1848 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1849 Xapian::TermIterator &end,
1852 int prefix_len = strlen (prefix);
1853 notmuch_string_list_t *list;
1855 list = _notmuch_string_list_create (ctx);
1856 if (unlikely (list == NULL))
1859 for (i.skip_to (prefix); i != end; i++) {
1860 /* Terminate loop at first term without desired prefix. */
1861 if (strncmp ((*i).c_str (), prefix, prefix_len))
1864 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1871 notmuch_database_get_all_tags (notmuch_database_t *db)
1873 Xapian::TermIterator i, end;
1874 notmuch_string_list_t *tags;
1877 i = db->xapian_db->allterms_begin();
1878 end = db->xapian_db->allterms_end();
1879 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1880 _find_prefix ("tag"));
1881 _notmuch_string_list_sort (tags);
1882 return _notmuch_tags_create (db, tags);
1883 } catch (const Xapian::Error &error) {
1884 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1885 error.get_msg().c_str());
1886 db->exception_reported = TRUE;