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 */
32 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
39 #define NOTMUCH_DATABASE_VERSION 1
41 #define STRINGIFY(s) _SUB_STRINGIFY(s)
42 #define _SUB_STRINGIFY(s) #s
44 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
46 * We currently have two different types of documents (mail and
47 * directory) and also some metadata.
51 * A mail document is associated with a particular email message file
52 * on disk. It is indexed with the following prefixed terms which the
53 * database uses to construct threads, etc.:
55 * Single terms of given prefix:
59 * id: Unique ID of mail. This is from the Message-ID header
60 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
61 * If it's present and too long, then we use
62 * "notmuch-sha1-<sha1_sum_of_message_id>".
63 * If this header is not present, we use
64 * "notmuch-sha1-<sha1_sum_of_entire_file>".
66 * thread: The ID of the thread to which the mail belongs
68 * replyto: The ID from the In-Reply-To header of the mail (if any).
70 * Multiple terms of given prefix:
72 * reference: All message IDs from In-Reply-To and References
73 * headers in the message.
75 * tag: Any tags associated with this message by the user.
77 * file-direntry: A colon-separated pair of values
78 * (INTEGER:STRING), where INTEGER is the
79 * document ID of a directory document, and
80 * STRING is the name of a file within that
81 * directory for this mail message.
83 * A mail document also has two values:
85 * TIMESTAMP: The time_t value corresponding to the message's
88 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
90 * In addition, terms from the content of the message are added with
91 * "from", "to", "attachment", and "subject" prefixes for use by the
92 * user in searching. Similarly, terms from the path of the mail
93 * message are added with a "folder" prefix. But the database doesn't
94 * really care itself about any of these.
96 * The data portion of a mail document is empty.
100 * A directory document is used by a client of the notmuch library to
101 * maintain data necessary to allow for efficient polling of mail
104 * All directory documents contain one term:
106 * directory: The directory path (relative to the database path)
107 * Or the SHA1 sum of the directory path (if the
108 * path itself is too long to fit in a Xapian
111 * And all directory documents for directories other than top-level
112 * directories also contain the following term:
114 * directory-direntry: A colon-separated pair of values
115 * (INTEGER:STRING), where INTEGER is the
116 * document ID of the parent directory
117 * document, and STRING is the name of this
118 * directory within that parent.
120 * All directory documents have a single value:
122 * TIMESTAMP: The mtime of the directory (at last scan)
124 * The data portion of a directory document contains the path of the
125 * directory (relative to the database path).
129 * Xapian allows us to store arbitrary name-value pairs as
130 * "metadata". We currently use the following metadata names with the
133 * version The database schema version, (which is distinct
134 * from both the notmuch package version (see
135 * notmuch --version) and the libnotmuch library
136 * version. The version is stored as an base-10
137 * ASCII integer. The initial database version
138 * was 1, (though a schema existed before that
139 * were no "version" database value existed at
140 * all). Successive versions are allocated as
141 * changes are made to the database (such as by
142 * indexing new fields).
144 * last_thread_id The last thread ID generated. This is stored
145 * as a 16-byte hexadecimal ASCII representation
146 * of a 64-bit unsigned integer. The first ID
147 * generated is 1 and the value will be
148 * incremented for each thread ID.
150 * thread_id_* A pre-allocated thread ID for a particular
151 * message. This is actually an arbitrarily large
152 * family of metadata name. Any particular name is
153 * formed by concatenating "thread_id_" with a message
154 * ID (or the SHA1 sum of a message ID if it is very
155 * long---see description of 'id' in the mail
156 * document). The value stored is a thread ID.
158 * These thread ID metadata values are stored
159 * whenever a message references a parent message
160 * that does not yet exist in the database. A
161 * thread ID will be allocated and stored, and if
162 * the message is later added, the stored thread
163 * ID will be used (and the metadata value will
166 * Even before a message is added, it's
167 * pre-allocated thread ID is useful so that all
168 * descendant messages that reference this common
169 * parent can be recognized as belonging to the
173 /* With these prefix values we follow the conventions published here:
175 * http://xapian.org/docs/omega/termprefixes.html
177 * as much as makes sense. Note that I took some liberty in matching
178 * the reserved prefix values to notmuch concepts, (for example, 'G'
179 * is documented as "newsGroup (or similar entity - e.g. a web forum
180 * name)", for which I think the thread is the closest analogue in
181 * notmuch. This in spite of the fact that we will eventually be
182 * storing mailing-list messages where 'G' for "mailing list name"
183 * might be even a closer analogue. I'm treating the single-character
184 * prefixes preferentially for core notmuch concepts (which will be
185 * nearly universal to all mail messages).
188 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
190 { "reference", "XREFERENCE" },
191 { "replyto", "XREPLYTO" },
192 { "directory", "XDIRECTORY" },
193 { "file-direntry", "XFDIRENTRY" },
194 { "directory-direntry", "XDDIRENTRY" },
197 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
204 static prefix_t PROBABILISTIC_PREFIX[]= {
207 { "attachment", "XATTACHMENT" },
208 { "subject", "XSUBJECT"},
209 { "folder", "XFOLDER"}
213 _internal_error (const char *format, ...)
217 va_start (va_args, format);
219 fprintf (stderr, "Internal error: ");
220 vfprintf (stderr, format, va_args);
228 _find_prefix (const char *name)
232 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
233 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
234 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
237 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
238 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
239 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
242 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
243 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
244 return PROBABILISTIC_PREFIX[i].prefix;
247 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
253 notmuch_status_to_string (notmuch_status_t status)
256 case NOTMUCH_STATUS_SUCCESS:
257 return "No error occurred";
258 case NOTMUCH_STATUS_OUT_OF_MEMORY:
259 return "Out of memory";
260 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
261 return "Attempt to write to a read-only database";
262 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
263 return "A Xapian exception occurred";
264 case NOTMUCH_STATUS_FILE_ERROR:
265 return "Something went wrong trying to read or write a file";
266 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
267 return "File is not an email";
268 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
269 return "Message ID is identical to a message in database";
270 case NOTMUCH_STATUS_NULL_POINTER:
271 return "Erroneous NULL pointer";
272 case NOTMUCH_STATUS_TAG_TOO_LONG:
273 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
274 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
275 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
276 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
277 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
279 case NOTMUCH_STATUS_LAST_STATUS:
280 return "Unknown error status value";
285 find_doc_ids_for_term (notmuch_database_t *notmuch,
287 Xapian::PostingIterator *begin,
288 Xapian::PostingIterator *end)
290 *begin = notmuch->xapian_db->postlist_begin (term);
292 *end = notmuch->xapian_db->postlist_end (term);
296 find_doc_ids (notmuch_database_t *notmuch,
297 const char *prefix_name,
299 Xapian::PostingIterator *begin,
300 Xapian::PostingIterator *end)
304 term = talloc_asprintf (notmuch, "%s%s",
305 _find_prefix (prefix_name), value);
307 find_doc_ids_for_term (notmuch, term, begin, end);
312 notmuch_private_status_t
313 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
314 const char *prefix_name,
316 unsigned int *doc_id)
318 Xapian::PostingIterator i, end;
320 find_doc_ids (notmuch, prefix_name, value, &i, &end);
324 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
329 #if DEBUG_DATABASE_SANITY
333 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
337 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
340 static Xapian::Document
341 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
343 return notmuch->xapian_db->get_document (doc_id);
346 /* Generate a compressed version of 'message_id' of the form:
348 * notmuch-sha1-<sha1_sum_of_message_id>
351 _message_id_compressed (void *ctx, const char *message_id)
353 char *sha1, *compressed;
355 sha1 = notmuch_sha1_of_string (message_id);
357 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
364 notmuch_database_find_message (notmuch_database_t *notmuch,
365 const char *message_id,
366 notmuch_message_t **message_ret)
368 notmuch_private_status_t status;
371 if (message_ret == NULL)
372 return NOTMUCH_STATUS_NULL_POINTER;
374 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
375 message_id = _message_id_compressed (notmuch, message_id);
378 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
379 message_id, &doc_id);
381 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
384 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
386 if (*message_ret == NULL)
387 return NOTMUCH_STATUS_OUT_OF_MEMORY;
390 return NOTMUCH_STATUS_SUCCESS;
391 } catch (const Xapian::Error &error) {
392 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
393 error.get_msg().c_str());
394 notmuch->exception_reported = TRUE;
396 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
400 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
401 * a (potentially nested) parenthesized sequence with '\' used to
402 * escape any character (including parentheses).
404 * If the sequence to be skipped continues to the end of the string,
405 * then 'str' will be left pointing at the final terminating '\0'
409 skip_space_and_comments (const char **str)
414 while (*s && (isspace (*s) || *s == '(')) {
415 while (*s && isspace (*s))
420 while (*s && nesting) {
423 } else if (*s == ')') {
425 } else if (*s == '\\') {
437 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
438 * comments, and the '<' and '>' delimiters.
440 * If not NULL, then *next will be made to point to the first character
441 * not parsed, (possibly pointing to the final '\0' terminator.
443 * Returns a newly talloc'ed string belonging to 'ctx'.
445 * Returns NULL if there is any error parsing the message-id. */
447 _parse_message_id (void *ctx, const char *message_id, const char **next)
452 if (message_id == NULL || *message_id == '\0')
457 skip_space_and_comments (&s);
459 /* Skip any unstructured text as well. */
460 while (*s && *s != '<')
471 skip_space_and_comments (&s);
474 while (*end && *end != '>')
483 if (end > s && *end == '>')
488 result = talloc_strndup (ctx, s, end - s + 1);
490 /* Finally, collapse any whitespace that is within the message-id
496 for (r = result, len = strlen (r); *r; r++, len--)
497 if (*r == ' ' || *r == '\t')
498 memmove (r, r+1, len);
504 /* Parse a References header value, putting a (talloc'ed under 'ctx')
505 * copy of each referenced message-id into 'hash'.
507 * We explicitly avoid including any reference identical to
508 * 'message_id' in the result (to avoid mass confusion when a single
509 * message references itself cyclically---and yes, mail messages are
510 * not infrequent in the wild that do this---don't ask me why).
513 parse_references (void *ctx,
514 const char *message_id,
520 if (refs == NULL || *refs == '\0')
524 ref = _parse_message_id (ctx, refs, &refs);
526 if (ref && strcmp (ref, message_id))
527 g_hash_table_insert (hash, ref, NULL);
532 notmuch_database_create (const char *path)
534 notmuch_database_t *notmuch = NULL;
535 char *notmuch_path = NULL;
540 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
544 err = stat (path, &st);
546 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
547 path, strerror (errno));
551 if (! S_ISDIR (st.st_mode)) {
552 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
557 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
559 err = mkdir (notmuch_path, 0755);
562 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
563 notmuch_path, strerror (errno));
567 notmuch = notmuch_database_open (path,
568 NOTMUCH_DATABASE_MODE_READ_WRITE);
569 notmuch_database_upgrade (notmuch, NULL, NULL);
573 talloc_free (notmuch_path);
579 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
581 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
582 fprintf (stderr, "Cannot write to a read-only database.\n");
583 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
586 return NOTMUCH_STATUS_SUCCESS;
590 notmuch_database_open (const char *path,
591 notmuch_database_mode_t mode)
593 notmuch_database_t *notmuch = NULL;
594 char *notmuch_path = NULL, *xapian_path = NULL;
597 unsigned int i, version;
599 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
601 fprintf (stderr, "Out of memory\n");
605 err = stat (notmuch_path, &st);
607 fprintf (stderr, "Error opening database at %s: %s\n",
608 notmuch_path, strerror (errno));
612 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
614 fprintf (stderr, "Out of memory\n");
618 notmuch = talloc (NULL, notmuch_database_t);
619 notmuch->exception_reported = FALSE;
620 notmuch->path = talloc_strdup (notmuch, path);
622 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
623 notmuch->path[strlen (notmuch->path) - 1] = '\0';
625 notmuch->needs_upgrade = FALSE;
626 notmuch->mode = mode;
627 notmuch->atomic_nesting = 0;
629 string last_thread_id;
631 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
632 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
633 Xapian::DB_CREATE_OR_OPEN);
634 version = notmuch_database_get_version (notmuch);
636 if (version > NOTMUCH_DATABASE_VERSION) {
638 "Error: Notmuch database at %s\n"
639 " has a newer database format version (%u) than supported by this\n"
640 " version of notmuch (%u). Refusing to open this database in\n"
641 " read-write mode.\n",
642 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
643 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
644 notmuch_database_close (notmuch);
649 if (version < NOTMUCH_DATABASE_VERSION)
650 notmuch->needs_upgrade = TRUE;
652 notmuch->xapian_db = new Xapian::Database (xapian_path);
653 version = notmuch_database_get_version (notmuch);
654 if (version > NOTMUCH_DATABASE_VERSION)
657 "Warning: Notmuch database at %s\n"
658 " has a newer database format version (%u) than supported by this\n"
659 " version of notmuch (%u). Some operations may behave incorrectly,\n"
660 " (but the database will not be harmed since it is being opened\n"
661 " in read-only mode).\n",
662 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
666 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
667 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
668 if (last_thread_id.empty ()) {
669 notmuch->last_thread_id = 0;
674 str = last_thread_id.c_str ();
675 notmuch->last_thread_id = strtoull (str, &end, 16);
677 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
680 notmuch->query_parser = new Xapian::QueryParser;
681 notmuch->term_gen = new Xapian::TermGenerator;
682 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
683 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
685 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
686 notmuch->query_parser->set_database (*notmuch->xapian_db);
687 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
688 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
689 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
691 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
692 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
693 notmuch->query_parser->add_boolean_prefix (prefix->name,
697 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
698 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
699 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
701 } catch (const Xapian::Error &error) {
702 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
703 error.get_msg().c_str());
717 notmuch_database_close (notmuch_database_t *notmuch)
720 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
721 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
722 } catch (const Xapian::Error &error) {
723 if (! notmuch->exception_reported) {
724 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
725 error.get_msg().c_str());
729 delete notmuch->term_gen;
730 delete notmuch->query_parser;
731 delete notmuch->xapian_db;
732 delete notmuch->value_range_processor;
733 talloc_free (notmuch);
737 notmuch_database_get_path (notmuch_database_t *notmuch)
739 return notmuch->path;
743 notmuch_database_get_version (notmuch_database_t *notmuch)
745 unsigned int version;
746 string version_string;
750 version_string = notmuch->xapian_db->get_metadata ("version");
751 if (version_string.empty ())
754 str = version_string.c_str ();
755 if (str == NULL || *str == '\0')
758 version = strtoul (str, &end, 10);
760 INTERNAL_ERROR ("Malformed database version: %s", str);
766 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
768 return notmuch->needs_upgrade;
771 static volatile sig_atomic_t do_progress_notify = 0;
774 handle_sigalrm (unused (int signal))
776 do_progress_notify = 1;
779 /* Upgrade the current database.
781 * After opening a database in read-write mode, the client should
782 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
783 * if so, upgrade with this function before making any modifications.
785 * The optional progress_notify callback can be used by the caller to
786 * provide progress indication to the user. If non-NULL it will be
787 * called periodically with 'count' as the number of messages upgraded
788 * so far and 'total' the overall number of messages that will be
792 notmuch_database_upgrade (notmuch_database_t *notmuch,
793 void (*progress_notify) (void *closure,
797 Xapian::WritableDatabase *db;
798 struct sigaction action;
799 struct itimerval timerval;
800 notmuch_bool_t timer_is_active = FALSE;
801 unsigned int version;
802 notmuch_status_t status;
803 unsigned int count = 0, total = 0;
805 status = _notmuch_database_ensure_writable (notmuch);
809 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
811 version = notmuch_database_get_version (notmuch);
813 if (version >= NOTMUCH_DATABASE_VERSION)
814 return NOTMUCH_STATUS_SUCCESS;
816 if (progress_notify) {
817 /* Setup our handler for SIGALRM */
818 memset (&action, 0, sizeof (struct sigaction));
819 action.sa_handler = handle_sigalrm;
820 sigemptyset (&action.sa_mask);
821 action.sa_flags = SA_RESTART;
822 sigaction (SIGALRM, &action, NULL);
824 /* Then start a timer to send SIGALRM once per second. */
825 timerval.it_interval.tv_sec = 1;
826 timerval.it_interval.tv_usec = 0;
827 timerval.it_value.tv_sec = 1;
828 timerval.it_value.tv_usec = 0;
829 setitimer (ITIMER_REAL, &timerval, NULL);
831 timer_is_active = TRUE;
834 /* Before version 1, each message document had its filename in the
835 * data field. Copy that into the new format by calling
836 * notmuch_message_add_filename.
839 notmuch_query_t *query = notmuch_query_create (notmuch, "");
840 notmuch_messages_t *messages;
841 notmuch_message_t *message;
843 Xapian::TermIterator t, t_end;
845 total = notmuch_query_count_messages (query);
847 for (messages = notmuch_query_search_messages (query);
848 notmuch_messages_valid (messages);
849 notmuch_messages_move_to_next (messages))
851 if (do_progress_notify) {
852 progress_notify (closure, (double) count / total);
853 do_progress_notify = 0;
856 message = notmuch_messages_get (messages);
858 filename = _notmuch_message_talloc_copy_data (message);
859 if (filename && *filename != '\0') {
860 _notmuch_message_add_filename (message, filename);
861 _notmuch_message_sync (message);
863 talloc_free (filename);
865 notmuch_message_destroy (message);
870 notmuch_query_destroy (query);
872 /* Also, before version 1 we stored directory timestamps in
873 * XTIMESTAMP documents instead of the current XDIRECTORY
874 * documents. So copy those as well. */
876 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
878 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
882 Xapian::PostingIterator p, p_end;
883 std::string term = *t;
885 p_end = notmuch->xapian_db->postlist_end (term);
887 for (p = notmuch->xapian_db->postlist_begin (term);
891 Xapian::Document document;
893 notmuch_directory_t *directory;
895 if (do_progress_notify) {
896 progress_notify (closure, (double) count / total);
897 do_progress_notify = 0;
900 document = find_document_for_doc_id (notmuch, *p);
901 mtime = Xapian::sortable_unserialise (
902 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
904 directory = notmuch_database_get_directory (notmuch,
906 notmuch_directory_set_mtime (directory, mtime);
907 notmuch_directory_destroy (directory);
912 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
915 /* Now that the upgrade is complete we can remove the old data
916 * and documents that are no longer needed. */
918 notmuch_query_t *query = notmuch_query_create (notmuch, "");
919 notmuch_messages_t *messages;
920 notmuch_message_t *message;
923 for (messages = notmuch_query_search_messages (query);
924 notmuch_messages_valid (messages);
925 notmuch_messages_move_to_next (messages))
927 if (do_progress_notify) {
928 progress_notify (closure, (double) count / total);
929 do_progress_notify = 0;
932 message = notmuch_messages_get (messages);
934 filename = _notmuch_message_talloc_copy_data (message);
935 if (filename && *filename != '\0') {
936 _notmuch_message_clear_data (message);
937 _notmuch_message_sync (message);
939 talloc_free (filename);
941 notmuch_message_destroy (message);
944 notmuch_query_destroy (query);
948 Xapian::TermIterator t, t_end;
950 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
952 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
956 Xapian::PostingIterator p, p_end;
957 std::string term = *t;
959 p_end = notmuch->xapian_db->postlist_end (term);
961 for (p = notmuch->xapian_db->postlist_begin (term);
965 if (do_progress_notify) {
966 progress_notify (closure, (double) count / total);
967 do_progress_notify = 0;
970 db->delete_document (*p);
975 if (timer_is_active) {
976 /* Now stop the timer. */
977 timerval.it_interval.tv_sec = 0;
978 timerval.it_interval.tv_usec = 0;
979 timerval.it_value.tv_sec = 0;
980 timerval.it_value.tv_usec = 0;
981 setitimer (ITIMER_REAL, &timerval, NULL);
983 /* And disable the signal handler. */
984 action.sa_handler = SIG_IGN;
985 sigaction (SIGALRM, &action, NULL);
988 return NOTMUCH_STATUS_SUCCESS;
992 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
994 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
995 notmuch->atomic_nesting > 0)
999 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1000 } catch (const Xapian::Error &error) {
1001 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1002 error.get_msg().c_str());
1003 notmuch->exception_reported = TRUE;
1004 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1008 notmuch->atomic_nesting++;
1009 return NOTMUCH_STATUS_SUCCESS;
1013 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1015 Xapian::WritableDatabase *db;
1017 if (notmuch->atomic_nesting == 0)
1018 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1020 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1021 notmuch->atomic_nesting > 1)
1024 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1026 db->commit_transaction ();
1028 /* This is a hack for testing. Xapian never flushes on a
1029 * non-flushed commit, even if the flush threshold is 1.
1030 * However, we rely on flushing to test atomicity. */
1031 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1032 if (thresh && atoi (thresh) == 1)
1034 } catch (const Xapian::Error &error) {
1035 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1036 error.get_msg().c_str());
1037 notmuch->exception_reported = TRUE;
1038 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1042 notmuch->atomic_nesting--;
1043 return NOTMUCH_STATUS_SUCCESS;
1046 /* We allow the user to use arbitrarily long paths for directories. But
1047 * we have a term-length limit. So if we exceed that, we'll use the
1048 * SHA-1 of the path for the database term.
1050 * Note: This function may return the original value of 'path'. If it
1051 * does not, then the caller is responsible to free() the returned
1055 _notmuch_database_get_directory_db_path (const char *path)
1057 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1059 if (term_len > NOTMUCH_TERM_MAX)
1060 return notmuch_sha1_of_string (path);
1065 /* Given a path, split it into two parts: the directory part is all
1066 * components except for the last, and the basename is that last
1067 * component. Getting the return-value for either part is optional
1068 * (the caller can pass NULL).
1070 * The original 'path' can represent either a regular file or a
1071 * directory---the splitting will be carried out in the same way in
1072 * either case. Trailing slashes on 'path' will be ignored, and any
1073 * cases of multiple '/' characters appearing in series will be
1074 * treated as a single '/'.
1076 * Allocation (if any) will have 'ctx' as the talloc owner. But
1077 * pointers will be returned within the original path string whenever
1080 * Note: If 'path' is non-empty and contains no non-trailing slash,
1081 * (that is, consists of a filename with no parent directory), then
1082 * the directory returned will be an empty string. However, if 'path'
1083 * is an empty string, then both directory and basename will be
1087 _notmuch_database_split_path (void *ctx,
1089 const char **directory,
1090 const char **basename)
1094 if (path == NULL || *path == '\0') {
1099 return NOTMUCH_STATUS_SUCCESS;
1102 /* Find the last slash (not counting a trailing slash), if any. */
1104 slash = path + strlen (path) - 1;
1106 /* First, skip trailing slashes. */
1107 while (slash != path) {
1114 /* Then, find a slash. */
1115 while (slash != path) {
1125 /* Finally, skip multiple slashes. */
1126 while (slash != path) {
1133 if (slash == path) {
1135 *directory = talloc_strdup (ctx, "");
1140 *directory = talloc_strndup (ctx, path, slash - path + 1);
1143 return NOTMUCH_STATUS_SUCCESS;
1147 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1149 unsigned int *directory_id)
1151 notmuch_directory_t *directory;
1152 notmuch_status_t status;
1156 return NOTMUCH_STATUS_SUCCESS;
1159 directory = _notmuch_directory_create (notmuch, path, &status);
1165 *directory_id = _notmuch_directory_get_document_id (directory);
1167 notmuch_directory_destroy (directory);
1169 return NOTMUCH_STATUS_SUCCESS;
1173 _notmuch_database_get_directory_path (void *ctx,
1174 notmuch_database_t *notmuch,
1175 unsigned int doc_id)
1177 Xapian::Document document;
1179 document = find_document_for_doc_id (notmuch, doc_id);
1181 return talloc_strdup (ctx, document.get_data ().c_str ());
1184 /* Given a legal 'filename' for the database, (either relative to
1185 * database path or absolute with initial components identical to
1186 * database path), return a new string (with 'ctx' as the talloc
1187 * owner) suitable for use as a direntry term value.
1189 * The necessary directory documents will be created in the database
1193 _notmuch_database_filename_to_direntry (void *ctx,
1194 notmuch_database_t *notmuch,
1195 const char *filename,
1198 const char *relative, *directory, *basename;
1199 Xapian::docid directory_id;
1200 notmuch_status_t status;
1202 relative = _notmuch_database_relative_path (notmuch, filename);
1204 status = _notmuch_database_split_path (ctx, relative,
1205 &directory, &basename);
1209 status = _notmuch_database_find_directory_id (notmuch, directory,
1214 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1216 return NOTMUCH_STATUS_SUCCESS;
1219 /* Given a legal 'path' for the database, return the relative path.
1221 * The return value will be a pointer to the original path contents,
1222 * and will be either the original string (if 'path' was relative) or
1223 * a portion of the string (if path was absolute and begins with the
1227 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1230 const char *db_path, *relative;
1231 unsigned int db_path_len;
1233 db_path = notmuch_database_get_path (notmuch);
1234 db_path_len = strlen (db_path);
1238 if (*relative == '/') {
1239 while (*relative == '/' && *(relative+1) == '/')
1242 if (strncmp (relative, db_path, db_path_len) == 0)
1244 relative += db_path_len;
1245 while (*relative == '/')
1253 notmuch_directory_t *
1254 notmuch_database_get_directory (notmuch_database_t *notmuch,
1257 notmuch_status_t status;
1260 return _notmuch_directory_create (notmuch, path, &status);
1261 } catch (const Xapian::Error &error) {
1262 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1263 error.get_msg().c_str());
1264 notmuch->exception_reported = TRUE;
1269 /* Allocate a document ID that satisfies the following criteria:
1271 * 1. The ID does not exist for any document in the Xapian database
1273 * 2. The ID was not previously returned from this function
1275 * 3. The ID is the smallest integer satisfying (1) and (2)
1277 * This function will trigger an internal error if these constraints
1278 * cannot all be satisfied, (that is, the pool of available document
1279 * IDs has been exhausted).
1282 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1284 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1286 notmuch->last_doc_id++;
1288 if (notmuch->last_doc_id == 0)
1289 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1291 return notmuch->last_doc_id;
1295 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1297 /* 16 bytes (+ terminator) for hexadecimal representation of
1298 * a 64-bit integer. */
1299 static char thread_id[17];
1300 Xapian::WritableDatabase *db;
1302 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1304 notmuch->last_thread_id++;
1306 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1308 db->set_metadata ("last_thread_id", thread_id);
1314 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1316 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1317 message_id = _message_id_compressed (ctx, message_id);
1319 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1323 /* Find the thread ID to which the message with 'message_id' belongs.
1325 * Note: 'thread_id_ret' must not be NULL!
1326 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1329 * Note: If there is no message in the database with the given
1330 * 'message_id' then a new thread_id will be allocated for this
1331 * message and stored in the database metadata, (where this same
1332 * thread ID can be looked up if the message is added to the database
1335 static notmuch_status_t
1336 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1338 const char *message_id,
1339 const char **thread_id_ret)
1341 notmuch_status_t status;
1342 notmuch_message_t *message;
1343 string thread_id_string;
1345 Xapian::WritableDatabase *db;
1347 status = notmuch_database_find_message (notmuch, message_id, &message);
1353 *thread_id_ret = talloc_steal (ctx,
1354 notmuch_message_get_thread_id (message));
1356 notmuch_message_destroy (message);
1358 return NOTMUCH_STATUS_SUCCESS;
1361 /* Message has not been seen yet.
1363 * We may have seen a reference to it already, in which case, we
1364 * can return the thread ID stored in the metadata. Otherwise, we
1365 * generate a new thread ID and store it there.
1367 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1368 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1369 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1371 if (thread_id_string.empty()) {
1372 *thread_id_ret = talloc_strdup (ctx,
1373 _notmuch_database_generate_thread_id (notmuch));
1374 db->set_metadata (metadata_key, *thread_id_ret);
1376 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1379 talloc_free (metadata_key);
1381 return NOTMUCH_STATUS_SUCCESS;
1384 static notmuch_status_t
1385 _merge_threads (notmuch_database_t *notmuch,
1386 const char *winner_thread_id,
1387 const char *loser_thread_id)
1389 Xapian::PostingIterator loser, loser_end;
1390 notmuch_message_t *message = NULL;
1391 notmuch_private_status_t private_status;
1392 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1394 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1396 for ( ; loser != loser_end; loser++) {
1397 message = _notmuch_message_create (notmuch, notmuch,
1398 *loser, &private_status);
1399 if (message == NULL) {
1400 ret = COERCE_STATUS (private_status,
1401 "Cannot find document for doc_id from query");
1405 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1406 _notmuch_message_add_term (message, "thread", winner_thread_id);
1407 _notmuch_message_sync (message);
1409 notmuch_message_destroy (message);
1415 notmuch_message_destroy (message);
1421 _my_talloc_free_for_g_hash (void *ptr)
1426 static notmuch_status_t
1427 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1428 notmuch_message_t *message,
1429 notmuch_message_file_t *message_file,
1430 const char **thread_id)
1432 GHashTable *parents = NULL;
1433 const char *refs, *in_reply_to, *in_reply_to_message_id;
1434 GList *l, *keys = NULL;
1435 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1437 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1438 _my_talloc_free_for_g_hash, NULL);
1440 refs = notmuch_message_file_get_header (message_file, "references");
1441 parse_references (message, notmuch_message_get_message_id (message),
1444 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1445 parse_references (message, notmuch_message_get_message_id (message),
1446 parents, in_reply_to);
1448 /* Carefully avoid adding any self-referential in-reply-to term. */
1449 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1450 if (in_reply_to_message_id &&
1451 strcmp (in_reply_to_message_id,
1452 notmuch_message_get_message_id (message)))
1454 _notmuch_message_add_term (message, "replyto",
1455 _parse_message_id (message, in_reply_to, NULL));
1458 keys = g_hash_table_get_keys (parents);
1459 for (l = keys; l; l = l->next) {
1460 char *parent_message_id;
1461 const char *parent_thread_id;
1463 parent_message_id = (char *) l->data;
1465 _notmuch_message_add_term (message, "reference",
1468 ret = _resolve_message_id_to_thread_id (notmuch,
1475 if (*thread_id == NULL) {
1476 *thread_id = talloc_strdup (message, parent_thread_id);
1477 _notmuch_message_add_term (message, "thread", *thread_id);
1478 } else if (strcmp (*thread_id, parent_thread_id)) {
1479 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1489 g_hash_table_unref (parents);
1494 static notmuch_status_t
1495 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1496 notmuch_message_t *message,
1497 const char **thread_id)
1499 const char *message_id = notmuch_message_get_message_id (message);
1500 Xapian::PostingIterator child, children_end;
1501 notmuch_message_t *child_message = NULL;
1502 const char *child_thread_id;
1503 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1504 notmuch_private_status_t private_status;
1506 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1508 for ( ; child != children_end; child++) {
1510 child_message = _notmuch_message_create (message, notmuch,
1511 *child, &private_status);
1512 if (child_message == NULL) {
1513 ret = COERCE_STATUS (private_status,
1514 "Cannot find document for doc_id from query");
1518 child_thread_id = notmuch_message_get_thread_id (child_message);
1519 if (*thread_id == NULL) {
1520 *thread_id = talloc_strdup (message, child_thread_id);
1521 _notmuch_message_add_term (message, "thread", *thread_id);
1522 } else if (strcmp (*thread_id, child_thread_id)) {
1523 _notmuch_message_remove_term (child_message, "reference",
1525 _notmuch_message_sync (child_message);
1526 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1531 notmuch_message_destroy (child_message);
1532 child_message = NULL;
1537 notmuch_message_destroy (child_message);
1542 /* Given a (mostly empty) 'message' and its corresponding
1543 * 'message_file' link it to existing threads in the database.
1545 * The first check is in the metadata of the database to see if we
1546 * have pre-allocated a thread_id in advance for this message, (which
1547 * would have happened if a message was previously added that
1548 * referenced this one).
1550 * Second, we look at 'message_file' and its link-relevant headers
1551 * (References and In-Reply-To) for message IDs.
1553 * Finally, we look in the database for existing message that
1554 * reference 'message'.
1556 * In all cases, we assign to the current message the first thread_id
1557 * found (through either parent or child). We will also merge any
1558 * existing, distinct threads where this message belongs to both,
1559 * (which is not uncommon when messages are processed out of order).
1561 * Finally, if no thread ID has been found through parent or child, we
1562 * call _notmuch_message_generate_thread_id to generate a new thread
1563 * ID. This should only happen for new, top-level messages, (no
1564 * References or In-Reply-To header in this message, and no previously
1565 * added message refers to this message).
1567 static notmuch_status_t
1568 _notmuch_database_link_message (notmuch_database_t *notmuch,
1569 notmuch_message_t *message,
1570 notmuch_message_file_t *message_file)
1572 notmuch_status_t status;
1573 const char *message_id, *thread_id = NULL;
1577 message_id = notmuch_message_get_message_id (message);
1578 metadata_key = _get_metadata_thread_id_key (message, message_id);
1580 /* Check if we have already seen related messages to this one.
1581 * If we have then use the thread_id that we stored at that time.
1583 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1584 if (! stored_id.empty()) {
1585 Xapian::WritableDatabase *db;
1587 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1589 /* Clear the metadata for this message ID. We don't need it
1591 db->set_metadata (metadata_key, "");
1592 thread_id = stored_id.c_str();
1594 _notmuch_message_add_term (message, "thread", thread_id);
1596 talloc_free (metadata_key);
1598 status = _notmuch_database_link_message_to_parents (notmuch, message,
1604 status = _notmuch_database_link_message_to_children (notmuch, message,
1609 /* If not part of any existing thread, generate a new thread ID. */
1610 if (thread_id == NULL) {
1611 thread_id = _notmuch_database_generate_thread_id (notmuch);
1613 _notmuch_message_add_term (message, "thread", thread_id);
1616 return NOTMUCH_STATUS_SUCCESS;
1620 notmuch_database_add_message (notmuch_database_t *notmuch,
1621 const char *filename,
1622 notmuch_message_t **message_ret)
1624 notmuch_message_file_t *message_file;
1625 notmuch_message_t *message = NULL;
1626 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1627 notmuch_private_status_t private_status;
1629 const char *date, *header;
1630 const char *from, *to, *subject;
1631 char *message_id = NULL;
1634 *message_ret = NULL;
1636 ret = _notmuch_database_ensure_writable (notmuch);
1640 message_file = notmuch_message_file_open (filename);
1641 if (message_file == NULL)
1642 return NOTMUCH_STATUS_FILE_ERROR;
1644 /* Adding a message may change many documents. Do this all
1646 ret = notmuch_database_begin_atomic (notmuch);
1650 notmuch_message_file_restrict_headers (message_file,
1661 /* Before we do any real work, (especially before doing a
1662 * potential SHA-1 computation on the entire file's contents),
1663 * let's make sure that what we're looking at looks like an
1664 * actual email message.
1666 from = notmuch_message_file_get_header (message_file, "from");
1667 subject = notmuch_message_file_get_header (message_file, "subject");
1668 to = notmuch_message_file_get_header (message_file, "to");
1670 if ((from == NULL || *from == '\0') &&
1671 (subject == NULL || *subject == '\0') &&
1672 (to == NULL || *to == '\0'))
1674 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1678 /* Now that we're sure it's mail, the first order of business
1679 * is to find a message ID (or else create one ourselves). */
1681 header = notmuch_message_file_get_header (message_file, "message-id");
1682 if (header && *header != '\0') {
1683 message_id = _parse_message_id (message_file, header, NULL);
1685 /* So the header value isn't RFC-compliant, but it's
1686 * better than no message-id at all. */
1687 if (message_id == NULL)
1688 message_id = talloc_strdup (message_file, header);
1690 /* If a message ID is too long, substitute its sha1 instead. */
1691 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1692 char *compressed = _message_id_compressed (message_file,
1694 talloc_free (message_id);
1695 message_id = compressed;
1699 if (message_id == NULL ) {
1700 /* No message-id at all, let's generate one by taking a
1701 * hash over the file's contents. */
1702 char *sha1 = notmuch_sha1_of_file (filename);
1704 /* If that failed too, something is really wrong. Give up. */
1706 ret = NOTMUCH_STATUS_FILE_ERROR;
1710 message_id = talloc_asprintf (message_file,
1711 "notmuch-sha1-%s", sha1);
1715 /* Now that we have a message ID, we get a message object,
1716 * (which may or may not reference an existing document in the
1719 message = _notmuch_message_create_for_message_id (notmuch,
1723 talloc_free (message_id);
1725 if (message == NULL) {
1726 ret = COERCE_STATUS (private_status,
1727 "Unexpected status value from _notmuch_message_create_for_message_id");
1731 _notmuch_message_add_filename (message, filename);
1733 /* Is this a newly created message object? */
1734 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1735 _notmuch_message_add_term (message, "type", "mail");
1737 ret = _notmuch_database_link_message (notmuch, message,
1742 date = notmuch_message_file_get_header (message_file, "date");
1743 _notmuch_message_set_date (message, date);
1745 _notmuch_message_index_file (message, filename);
1747 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1750 _notmuch_message_sync (message);
1751 } catch (const Xapian::Error &error) {
1752 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1753 error.get_msg().c_str());
1754 notmuch->exception_reported = TRUE;
1755 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1761 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1762 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1763 *message_ret = message;
1765 notmuch_message_destroy (message);
1769 notmuch_message_file_close (message_file);
1771 ret2 = notmuch_database_end_atomic (notmuch);
1772 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1773 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
1774 ret2 != NOTMUCH_STATUS_SUCCESS)
1781 notmuch_database_remove_message (notmuch_database_t *notmuch,
1782 const char *filename)
1784 notmuch_status_t status;
1785 notmuch_message_t *message;
1787 status = notmuch_database_find_message_by_filename (notmuch, filename,
1790 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1791 status = _notmuch_message_remove_filename (message, filename);
1792 if (status == NOTMUCH_STATUS_SUCCESS)
1793 _notmuch_message_delete (message);
1794 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1795 _notmuch_message_sync (message);
1797 notmuch_message_destroy (message);
1804 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1805 const char *filename,
1806 notmuch_message_t **message_ret)
1809 const char *prefix = _find_prefix ("file-direntry");
1810 char *direntry, *term;
1811 Xapian::PostingIterator i, end;
1812 notmuch_status_t status;
1814 if (message_ret == NULL)
1815 return NOTMUCH_STATUS_NULL_POINTER;
1817 local = talloc_new (notmuch);
1820 status = _notmuch_database_filename_to_direntry (local, notmuch,
1821 filename, &direntry);
1825 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1827 find_doc_ids_for_term (notmuch, term, &i, &end);
1830 notmuch_private_status_t private_status;
1832 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1834 if (*message_ret == NULL)
1835 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1837 } catch (const Xapian::Error &error) {
1838 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
1839 error.get_msg().c_str());
1840 notmuch->exception_reported = TRUE;
1841 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1845 talloc_free (local);
1847 if (status && *message_ret) {
1848 notmuch_message_destroy (*message_ret);
1849 *message_ret = NULL;
1854 notmuch_string_list_t *
1855 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1856 Xapian::TermIterator &end,
1859 int prefix_len = strlen (prefix);
1860 notmuch_string_list_t *list;
1862 list = _notmuch_string_list_create (ctx);
1863 if (unlikely (list == NULL))
1866 for (i.skip_to (prefix); i != end; i++) {
1867 /* Terminate loop at first term without desired prefix. */
1868 if (strncmp ((*i).c_str (), prefix, prefix_len))
1871 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1878 notmuch_database_get_all_tags (notmuch_database_t *db)
1880 Xapian::TermIterator i, end;
1881 notmuch_string_list_t *tags;
1884 i = db->xapian_db->allterms_begin();
1885 end = db->xapian_db->allterms_end();
1886 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1887 _find_prefix ("tag"));
1888 _notmuch_string_list_sort (tags);
1889 return _notmuch_tags_create (db, tags);
1890 } catch (const Xapian::Error &error) {
1891 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1892 error.get_msg().c_str());
1893 db->exception_reported = TRUE;