1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see http://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
28 #include <glib.h> /* g_free, GPtrArray, GHashTable */
29 #include <glib-object.h> /* g_type_init */
31 #include <gmime/gmime.h> /* g_mime_init */
35 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
42 #define NOTMUCH_DATABASE_VERSION 1
44 #define STRINGIFY(s) _SUB_STRINGIFY(s)
45 #define _SUB_STRINGIFY(s) #s
47 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
49 * We currently have two different types of documents (mail and
50 * directory) and also some metadata.
54 * A mail document is associated with a particular email message file
55 * on disk. It is indexed with the following prefixed terms which the
56 * database uses to construct threads, etc.:
58 * Single terms of given prefix:
62 * id: Unique ID of mail. This is from the Message-ID header
63 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
64 * If it's present and too long, then we use
65 * "notmuch-sha1-<sha1_sum_of_message_id>".
66 * If this header is not present, we use
67 * "notmuch-sha1-<sha1_sum_of_entire_file>".
69 * thread: The ID of the thread to which the mail belongs
71 * replyto: The ID from the In-Reply-To header of the mail (if any).
73 * Multiple terms of given prefix:
75 * reference: All message IDs from In-Reply-To and References
76 * headers in the message.
78 * tag: Any tags associated with this message by the user.
80 * file-direntry: A colon-separated pair of values
81 * (INTEGER:STRING), where INTEGER is the
82 * document ID of a directory document, and
83 * STRING is the name of a file within that
84 * directory for this mail message.
86 * A mail document also has four values:
88 * TIMESTAMP: The time_t value corresponding to the message's
91 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
93 * FROM: The value of the "From" header
95 * SUBJECT: The value of the "Subject" header
97 * In addition, terms from the content of the message are added with
98 * "from", "to", "attachment", and "subject" prefixes for use by the
99 * user in searching. Similarly, terms from the path of the mail
100 * message are added with a "folder" prefix. But the database doesn't
101 * really care itself about any of these.
103 * The data portion of a mail document is empty.
107 * A directory document is used by a client of the notmuch library to
108 * maintain data necessary to allow for efficient polling of mail
111 * All directory documents contain one term:
113 * directory: The directory path (relative to the database path)
114 * Or the SHA1 sum of the directory path (if the
115 * path itself is too long to fit in a Xapian
118 * And all directory documents for directories other than top-level
119 * directories also contain the following term:
121 * directory-direntry: A colon-separated pair of values
122 * (INTEGER:STRING), where INTEGER is the
123 * document ID of the parent directory
124 * document, and STRING is the name of this
125 * directory within that parent.
127 * All directory documents have a single value:
129 * TIMESTAMP: The mtime of the directory (at last scan)
131 * The data portion of a directory document contains the path of the
132 * directory (relative to the database path).
136 * Xapian allows us to store arbitrary name-value pairs as
137 * "metadata". We currently use the following metadata names with the
140 * version The database schema version, (which is distinct
141 * from both the notmuch package version (see
142 * notmuch --version) and the libnotmuch library
143 * version. The version is stored as an base-10
144 * ASCII integer. The initial database version
145 * was 1, (though a schema existed before that
146 * were no "version" database value existed at
147 * all). Successive versions are allocated as
148 * changes are made to the database (such as by
149 * indexing new fields).
151 * last_thread_id The last thread ID generated. This is stored
152 * as a 16-byte hexadecimal ASCII representation
153 * of a 64-bit unsigned integer. The first ID
154 * generated is 1 and the value will be
155 * incremented for each thread ID.
157 * thread_id_* A pre-allocated thread ID for a particular
158 * message. This is actually an arbitrarily large
159 * family of metadata name. Any particular name is
160 * formed by concatenating "thread_id_" with a message
161 * ID (or the SHA1 sum of a message ID if it is very
162 * long---see description of 'id' in the mail
163 * document). The value stored is a thread ID.
165 * These thread ID metadata values are stored
166 * whenever a message references a parent message
167 * that does not yet exist in the database. A
168 * thread ID will be allocated and stored, and if
169 * the message is later added, the stored thread
170 * ID will be used (and the metadata value will
173 * Even before a message is added, it's
174 * pre-allocated thread ID is useful so that all
175 * descendant messages that reference this common
176 * parent can be recognized as belonging to the
180 /* With these prefix values we follow the conventions published here:
182 * http://xapian.org/docs/omega/termprefixes.html
184 * as much as makes sense. Note that I took some liberty in matching
185 * the reserved prefix values to notmuch concepts, (for example, 'G'
186 * is documented as "newsGroup (or similar entity - e.g. a web forum
187 * name)", for which I think the thread is the closest analogue in
188 * notmuch. This in spite of the fact that we will eventually be
189 * storing mailing-list messages where 'G' for "mailing list name"
190 * might be even a closer analogue. I'm treating the single-character
191 * prefixes preferentially for core notmuch concepts (which will be
192 * nearly universal to all mail messages).
195 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
197 { "reference", "XREFERENCE" },
198 { "replyto", "XREPLYTO" },
199 { "directory", "XDIRECTORY" },
200 { "file-direntry", "XFDIRENTRY" },
201 { "directory-direntry", "XDDIRENTRY" },
204 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
211 static prefix_t PROBABILISTIC_PREFIX[]= {
214 { "attachment", "XATTACHMENT" },
215 { "subject", "XSUBJECT"},
216 { "folder", "XFOLDER"}
220 _find_prefix (const char *name)
224 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
225 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
226 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
229 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
230 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
231 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
234 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
235 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
236 return PROBABILISTIC_PREFIX[i].prefix;
239 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
245 notmuch_status_to_string (notmuch_status_t status)
248 case NOTMUCH_STATUS_SUCCESS:
249 return "No error occurred";
250 case NOTMUCH_STATUS_OUT_OF_MEMORY:
251 return "Out of memory";
252 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
253 return "Attempt to write to a read-only database";
254 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
255 return "A Xapian exception occurred";
256 case NOTMUCH_STATUS_FILE_ERROR:
257 return "Something went wrong trying to read or write a file";
258 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
259 return "File is not an email";
260 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
261 return "Message ID is identical to a message in database";
262 case NOTMUCH_STATUS_NULL_POINTER:
263 return "Erroneous NULL pointer";
264 case NOTMUCH_STATUS_TAG_TOO_LONG:
265 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
266 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
267 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
268 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
269 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
271 case NOTMUCH_STATUS_LAST_STATUS:
272 return "Unknown error status value";
277 find_doc_ids_for_term (notmuch_database_t *notmuch,
279 Xapian::PostingIterator *begin,
280 Xapian::PostingIterator *end)
282 *begin = notmuch->xapian_db->postlist_begin (term);
284 *end = notmuch->xapian_db->postlist_end (term);
288 find_doc_ids (notmuch_database_t *notmuch,
289 const char *prefix_name,
291 Xapian::PostingIterator *begin,
292 Xapian::PostingIterator *end)
296 term = talloc_asprintf (notmuch, "%s%s",
297 _find_prefix (prefix_name), value);
299 find_doc_ids_for_term (notmuch, term, begin, end);
304 notmuch_private_status_t
305 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
306 const char *prefix_name,
308 unsigned int *doc_id)
310 Xapian::PostingIterator i, end;
312 find_doc_ids (notmuch, prefix_name, value, &i, &end);
316 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
321 #if DEBUG_DATABASE_SANITY
325 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
329 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
332 static Xapian::Document
333 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
335 return notmuch->xapian_db->get_document (doc_id);
338 /* Generate a compressed version of 'message_id' of the form:
340 * notmuch-sha1-<sha1_sum_of_message_id>
343 _message_id_compressed (void *ctx, const char *message_id)
345 char *sha1, *compressed;
347 sha1 = notmuch_sha1_of_string (message_id);
349 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
356 notmuch_database_find_message (notmuch_database_t *notmuch,
357 const char *message_id,
358 notmuch_message_t **message_ret)
360 notmuch_private_status_t status;
363 if (message_ret == NULL)
364 return NOTMUCH_STATUS_NULL_POINTER;
366 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
367 message_id = _message_id_compressed (notmuch, message_id);
370 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
371 message_id, &doc_id);
373 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
376 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
378 if (*message_ret == NULL)
379 return NOTMUCH_STATUS_OUT_OF_MEMORY;
382 return NOTMUCH_STATUS_SUCCESS;
383 } catch (const Xapian::Error &error) {
384 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
385 error.get_msg().c_str());
386 notmuch->exception_reported = TRUE;
388 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
392 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
393 * a (potentially nested) parenthesized sequence with '\' used to
394 * escape any character (including parentheses).
396 * If the sequence to be skipped continues to the end of the string,
397 * then 'str' will be left pointing at the final terminating '\0'
401 skip_space_and_comments (const char **str)
406 while (*s && (isspace (*s) || *s == '(')) {
407 while (*s && isspace (*s))
412 while (*s && nesting) {
415 } else if (*s == ')') {
417 } else if (*s == '\\') {
429 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
430 * comments, and the '<' and '>' delimiters.
432 * If not NULL, then *next will be made to point to the first character
433 * not parsed, (possibly pointing to the final '\0' terminator.
435 * Returns a newly talloc'ed string belonging to 'ctx'.
437 * Returns NULL if there is any error parsing the message-id. */
439 _parse_message_id (void *ctx, const char *message_id, const char **next)
444 if (message_id == NULL || *message_id == '\0')
449 skip_space_and_comments (&s);
451 /* Skip any unstructured text as well. */
452 while (*s && *s != '<')
463 skip_space_and_comments (&s);
466 while (*end && *end != '>')
475 if (end > s && *end == '>')
480 result = talloc_strndup (ctx, s, end - s + 1);
482 /* Finally, collapse any whitespace that is within the message-id
488 for (r = result, len = strlen (r); *r; r++, len--)
489 if (*r == ' ' || *r == '\t')
490 memmove (r, r+1, len);
496 /* Parse a References header value, putting a (talloc'ed under 'ctx')
497 * copy of each referenced message-id into 'hash'.
499 * We explicitly avoid including any reference identical to
500 * 'message_id' in the result (to avoid mass confusion when a single
501 * message references itself cyclically---and yes, mail messages are
502 * not infrequent in the wild that do this---don't ask me why).
505 parse_references (void *ctx,
506 const char *message_id,
512 if (refs == NULL || *refs == '\0')
516 ref = _parse_message_id (ctx, refs, &refs);
518 if (ref && strcmp (ref, message_id))
519 g_hash_table_insert (hash, ref, NULL);
524 notmuch_database_create (const char *path, notmuch_database_t **database)
526 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
527 notmuch_database_t *notmuch = NULL;
528 char *notmuch_path = NULL;
533 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
534 status = NOTMUCH_STATUS_NULL_POINTER;
538 err = stat (path, &st);
540 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
541 path, strerror (errno));
542 status = NOTMUCH_STATUS_FILE_ERROR;
546 if (! S_ISDIR (st.st_mode)) {
547 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
549 status = NOTMUCH_STATUS_FILE_ERROR;
553 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
555 err = mkdir (notmuch_path, 0755);
558 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
559 notmuch_path, strerror (errno));
560 status = NOTMUCH_STATUS_FILE_ERROR;
564 status = notmuch_database_open (path,
565 NOTMUCH_DATABASE_MODE_READ_WRITE,
569 status = notmuch_database_upgrade (notmuch, NULL, NULL);
571 notmuch_database_close(notmuch);
577 talloc_free (notmuch_path);
582 talloc_free (notmuch);
587 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
589 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
590 fprintf (stderr, "Cannot write to a read-only database.\n");
591 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
594 return NOTMUCH_STATUS_SUCCESS;
598 notmuch_database_open (const char *path,
599 notmuch_database_mode_t mode,
600 notmuch_database_t **database)
602 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
603 void *local = talloc_new (NULL);
604 notmuch_database_t *notmuch = NULL;
605 char *notmuch_path, *xapian_path;
608 unsigned int i, version;
609 static int initialized = 0;
612 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
613 status = NOTMUCH_STATUS_NULL_POINTER;
617 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
618 fprintf (stderr, "Out of memory\n");
619 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
623 err = stat (notmuch_path, &st);
625 fprintf (stderr, "Error opening database at %s: %s\n",
626 notmuch_path, strerror (errno));
627 status = NOTMUCH_STATUS_FILE_ERROR;
631 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
632 fprintf (stderr, "Out of memory\n");
633 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
637 /* Initialize the GLib type system and threads */
640 /* Initialize gmime */
646 notmuch = talloc_zero (NULL, notmuch_database_t);
647 notmuch->exception_reported = FALSE;
648 notmuch->path = talloc_strdup (notmuch, path);
650 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
651 notmuch->path[strlen (notmuch->path) - 1] = '\0';
653 notmuch->needs_upgrade = FALSE;
654 notmuch->mode = mode;
655 notmuch->atomic_nesting = 0;
657 string last_thread_id;
659 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
660 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
661 Xapian::DB_CREATE_OR_OPEN);
662 version = notmuch_database_get_version (notmuch);
664 if (version > NOTMUCH_DATABASE_VERSION) {
666 "Error: Notmuch database at %s\n"
667 " has a newer database format version (%u) than supported by this\n"
668 " version of notmuch (%u). Refusing to open this database in\n"
669 " read-write mode.\n",
670 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
671 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
672 notmuch_database_destroy (notmuch);
674 status = NOTMUCH_STATUS_FILE_ERROR;
678 if (version < NOTMUCH_DATABASE_VERSION)
679 notmuch->needs_upgrade = TRUE;
681 notmuch->xapian_db = new Xapian::Database (xapian_path);
682 version = notmuch_database_get_version (notmuch);
683 if (version > NOTMUCH_DATABASE_VERSION)
686 "Warning: Notmuch database at %s\n"
687 " has a newer database format version (%u) than supported by this\n"
688 " version of notmuch (%u). Some operations may behave incorrectly,\n"
689 " (but the database will not be harmed since it is being opened\n"
690 " in read-only mode).\n",
691 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
695 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
696 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
697 if (last_thread_id.empty ()) {
698 notmuch->last_thread_id = 0;
703 str = last_thread_id.c_str ();
704 notmuch->last_thread_id = strtoull (str, &end, 16);
706 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
709 notmuch->query_parser = new Xapian::QueryParser;
710 notmuch->term_gen = new Xapian::TermGenerator;
711 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
712 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
714 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
715 notmuch->query_parser->set_database (*notmuch->xapian_db);
716 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
717 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
718 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
720 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
721 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
722 notmuch->query_parser->add_boolean_prefix (prefix->name,
726 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
727 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
728 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
730 } catch (const Xapian::Error &error) {
731 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
732 error.get_msg().c_str());
733 notmuch_database_destroy (notmuch);
735 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
744 talloc_free (notmuch);
749 notmuch_database_close (notmuch_database_t *notmuch)
752 if (notmuch->xapian_db != NULL &&
753 notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
754 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
755 } catch (const Xapian::Error &error) {
756 if (! notmuch->exception_reported) {
757 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
758 error.get_msg().c_str());
762 /* Many Xapian objects (and thus notmuch objects) hold references to
763 * the database, so merely deleting the database may not suffice to
764 * close it. Thus, we explicitly close it here. */
765 if (notmuch->xapian_db != NULL) {
767 notmuch->xapian_db->close();
768 } catch (const Xapian::Error &error) {
773 delete notmuch->term_gen;
774 notmuch->term_gen = NULL;
775 delete notmuch->query_parser;
776 notmuch->query_parser = NULL;
777 delete notmuch->xapian_db;
778 notmuch->xapian_db = NULL;
779 delete notmuch->value_range_processor;
780 notmuch->value_range_processor = NULL;
784 notmuch_database_destroy (notmuch_database_t *notmuch)
786 notmuch_database_close (notmuch);
787 talloc_free (notmuch);
791 notmuch_database_get_path (notmuch_database_t *notmuch)
793 return notmuch->path;
797 notmuch_database_get_version (notmuch_database_t *notmuch)
799 unsigned int version;
800 string version_string;
804 version_string = notmuch->xapian_db->get_metadata ("version");
805 if (version_string.empty ())
808 str = version_string.c_str ();
809 if (str == NULL || *str == '\0')
812 version = strtoul (str, &end, 10);
814 INTERNAL_ERROR ("Malformed database version: %s", str);
820 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
822 return notmuch->needs_upgrade;
825 static volatile sig_atomic_t do_progress_notify = 0;
828 handle_sigalrm (unused (int signal))
830 do_progress_notify = 1;
833 /* Upgrade the current database.
835 * After opening a database in read-write mode, the client should
836 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
837 * if so, upgrade with this function before making any modifications.
839 * The optional progress_notify callback can be used by the caller to
840 * provide progress indication to the user. If non-NULL it will be
841 * called periodically with 'count' as the number of messages upgraded
842 * so far and 'total' the overall number of messages that will be
846 notmuch_database_upgrade (notmuch_database_t *notmuch,
847 void (*progress_notify) (void *closure,
851 Xapian::WritableDatabase *db;
852 struct sigaction action;
853 struct itimerval timerval;
854 notmuch_bool_t timer_is_active = FALSE;
855 unsigned int version;
856 notmuch_status_t status;
857 unsigned int count = 0, total = 0;
859 status = _notmuch_database_ensure_writable (notmuch);
863 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
865 version = notmuch_database_get_version (notmuch);
867 if (version >= NOTMUCH_DATABASE_VERSION)
868 return NOTMUCH_STATUS_SUCCESS;
870 if (progress_notify) {
871 /* Setup our handler for SIGALRM */
872 memset (&action, 0, sizeof (struct sigaction));
873 action.sa_handler = handle_sigalrm;
874 sigemptyset (&action.sa_mask);
875 action.sa_flags = SA_RESTART;
876 sigaction (SIGALRM, &action, NULL);
878 /* Then start a timer to send SIGALRM once per second. */
879 timerval.it_interval.tv_sec = 1;
880 timerval.it_interval.tv_usec = 0;
881 timerval.it_value.tv_sec = 1;
882 timerval.it_value.tv_usec = 0;
883 setitimer (ITIMER_REAL, &timerval, NULL);
885 timer_is_active = TRUE;
888 /* Before version 1, each message document had its filename in the
889 * data field. Copy that into the new format by calling
890 * notmuch_message_add_filename.
893 notmuch_query_t *query = notmuch_query_create (notmuch, "");
894 notmuch_messages_t *messages;
895 notmuch_message_t *message;
897 Xapian::TermIterator t, t_end;
899 total = notmuch_query_count_messages (query);
901 for (messages = notmuch_query_search_messages (query);
902 notmuch_messages_valid (messages);
903 notmuch_messages_move_to_next (messages))
905 if (do_progress_notify) {
906 progress_notify (closure, (double) count / total);
907 do_progress_notify = 0;
910 message = notmuch_messages_get (messages);
912 filename = _notmuch_message_talloc_copy_data (message);
913 if (filename && *filename != '\0') {
914 _notmuch_message_add_filename (message, filename);
915 _notmuch_message_sync (message);
917 talloc_free (filename);
919 notmuch_message_destroy (message);
924 notmuch_query_destroy (query);
926 /* Also, before version 1 we stored directory timestamps in
927 * XTIMESTAMP documents instead of the current XDIRECTORY
928 * documents. So copy those as well. */
930 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
932 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
936 Xapian::PostingIterator p, p_end;
937 std::string term = *t;
939 p_end = notmuch->xapian_db->postlist_end (term);
941 for (p = notmuch->xapian_db->postlist_begin (term);
945 Xapian::Document document;
947 notmuch_directory_t *directory;
949 if (do_progress_notify) {
950 progress_notify (closure, (double) count / total);
951 do_progress_notify = 0;
954 document = find_document_for_doc_id (notmuch, *p);
955 mtime = Xapian::sortable_unserialise (
956 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
958 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
959 NOTMUCH_FIND_CREATE, &status);
960 notmuch_directory_set_mtime (directory, mtime);
961 notmuch_directory_destroy (directory);
966 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
969 /* Now that the upgrade is complete we can remove the old data
970 * and documents that are no longer needed. */
972 notmuch_query_t *query = notmuch_query_create (notmuch, "");
973 notmuch_messages_t *messages;
974 notmuch_message_t *message;
977 for (messages = notmuch_query_search_messages (query);
978 notmuch_messages_valid (messages);
979 notmuch_messages_move_to_next (messages))
981 if (do_progress_notify) {
982 progress_notify (closure, (double) count / total);
983 do_progress_notify = 0;
986 message = notmuch_messages_get (messages);
988 filename = _notmuch_message_talloc_copy_data (message);
989 if (filename && *filename != '\0') {
990 _notmuch_message_clear_data (message);
991 _notmuch_message_sync (message);
993 talloc_free (filename);
995 notmuch_message_destroy (message);
998 notmuch_query_destroy (query);
1002 Xapian::TermIterator t, t_end;
1004 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1006 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1010 Xapian::PostingIterator p, p_end;
1011 std::string term = *t;
1013 p_end = notmuch->xapian_db->postlist_end (term);
1015 for (p = notmuch->xapian_db->postlist_begin (term);
1019 if (do_progress_notify) {
1020 progress_notify (closure, (double) count / total);
1021 do_progress_notify = 0;
1024 db->delete_document (*p);
1029 if (timer_is_active) {
1030 /* Now stop the timer. */
1031 timerval.it_interval.tv_sec = 0;
1032 timerval.it_interval.tv_usec = 0;
1033 timerval.it_value.tv_sec = 0;
1034 timerval.it_value.tv_usec = 0;
1035 setitimer (ITIMER_REAL, &timerval, NULL);
1037 /* And disable the signal handler. */
1038 action.sa_handler = SIG_IGN;
1039 sigaction (SIGALRM, &action, NULL);
1042 return NOTMUCH_STATUS_SUCCESS;
1046 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1048 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1049 notmuch->atomic_nesting > 0)
1053 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1054 } catch (const Xapian::Error &error) {
1055 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1056 error.get_msg().c_str());
1057 notmuch->exception_reported = TRUE;
1058 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1062 notmuch->atomic_nesting++;
1063 return NOTMUCH_STATUS_SUCCESS;
1067 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1069 Xapian::WritableDatabase *db;
1071 if (notmuch->atomic_nesting == 0)
1072 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1074 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1075 notmuch->atomic_nesting > 1)
1078 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1080 db->commit_transaction ();
1082 /* This is a hack for testing. Xapian never flushes on a
1083 * non-flushed commit, even if the flush threshold is 1.
1084 * However, we rely on flushing to test atomicity. */
1085 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1086 if (thresh && atoi (thresh) == 1)
1088 } catch (const Xapian::Error &error) {
1089 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1090 error.get_msg().c_str());
1091 notmuch->exception_reported = TRUE;
1092 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1096 notmuch->atomic_nesting--;
1097 return NOTMUCH_STATUS_SUCCESS;
1100 /* We allow the user to use arbitrarily long paths for directories. But
1101 * we have a term-length limit. So if we exceed that, we'll use the
1102 * SHA-1 of the path for the database term.
1104 * Note: This function may return the original value of 'path'. If it
1105 * does not, then the caller is responsible to free() the returned
1109 _notmuch_database_get_directory_db_path (const char *path)
1111 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1113 if (term_len > NOTMUCH_TERM_MAX)
1114 return notmuch_sha1_of_string (path);
1119 /* Given a path, split it into two parts: the directory part is all
1120 * components except for the last, and the basename is that last
1121 * component. Getting the return-value for either part is optional
1122 * (the caller can pass NULL).
1124 * The original 'path' can represent either a regular file or a
1125 * directory---the splitting will be carried out in the same way in
1126 * either case. Trailing slashes on 'path' will be ignored, and any
1127 * cases of multiple '/' characters appearing in series will be
1128 * treated as a single '/'.
1130 * Allocation (if any) will have 'ctx' as the talloc owner. But
1131 * pointers will be returned within the original path string whenever
1134 * Note: If 'path' is non-empty and contains no non-trailing slash,
1135 * (that is, consists of a filename with no parent directory), then
1136 * the directory returned will be an empty string. However, if 'path'
1137 * is an empty string, then both directory and basename will be
1141 _notmuch_database_split_path (void *ctx,
1143 const char **directory,
1144 const char **basename)
1148 if (path == NULL || *path == '\0') {
1153 return NOTMUCH_STATUS_SUCCESS;
1156 /* Find the last slash (not counting a trailing slash), if any. */
1158 slash = path + strlen (path) - 1;
1160 /* First, skip trailing slashes. */
1161 while (slash != path) {
1168 /* Then, find a slash. */
1169 while (slash != path) {
1179 /* Finally, skip multiple slashes. */
1180 while (slash != path) {
1187 if (slash == path) {
1189 *directory = talloc_strdup (ctx, "");
1194 *directory = talloc_strndup (ctx, path, slash - path + 1);
1197 return NOTMUCH_STATUS_SUCCESS;
1200 /* Find the document ID of the specified directory.
1202 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1203 * created if one does not exist for 'path'. Otherwise, if the
1204 * directory document does not exist, this sets *directory_id to
1205 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1208 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1210 notmuch_find_flags_t flags,
1211 unsigned int *directory_id)
1213 notmuch_directory_t *directory;
1214 notmuch_status_t status;
1218 return NOTMUCH_STATUS_SUCCESS;
1221 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1222 if (status || !directory) {
1227 *directory_id = _notmuch_directory_get_document_id (directory);
1229 notmuch_directory_destroy (directory);
1231 return NOTMUCH_STATUS_SUCCESS;
1235 _notmuch_database_get_directory_path (void *ctx,
1236 notmuch_database_t *notmuch,
1237 unsigned int doc_id)
1239 Xapian::Document document;
1241 document = find_document_for_doc_id (notmuch, doc_id);
1243 return talloc_strdup (ctx, document.get_data ().c_str ());
1246 /* Given a legal 'filename' for the database, (either relative to
1247 * database path or absolute with initial components identical to
1248 * database path), return a new string (with 'ctx' as the talloc
1249 * owner) suitable for use as a direntry term value.
1251 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1252 * will be created in the database as needed. Otherwise, if the
1253 * necessary directory documents do not exist, this sets
1254 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1257 _notmuch_database_filename_to_direntry (void *ctx,
1258 notmuch_database_t *notmuch,
1259 const char *filename,
1260 notmuch_find_flags_t flags,
1263 const char *relative, *directory, *basename;
1264 Xapian::docid directory_id;
1265 notmuch_status_t status;
1267 relative = _notmuch_database_relative_path (notmuch, filename);
1269 status = _notmuch_database_split_path (ctx, relative,
1270 &directory, &basename);
1274 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1276 if (status || directory_id == (unsigned int)-1) {
1281 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1283 return NOTMUCH_STATUS_SUCCESS;
1286 /* Given a legal 'path' for the database, return the relative path.
1288 * The return value will be a pointer to the original path contents,
1289 * and will be either the original string (if 'path' was relative) or
1290 * a portion of the string (if path was absolute and begins with the
1294 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1297 const char *db_path, *relative;
1298 unsigned int db_path_len;
1300 db_path = notmuch_database_get_path (notmuch);
1301 db_path_len = strlen (db_path);
1305 if (*relative == '/') {
1306 while (*relative == '/' && *(relative+1) == '/')
1309 if (strncmp (relative, db_path, db_path_len) == 0)
1311 relative += db_path_len;
1312 while (*relative == '/')
1321 notmuch_database_get_directory (notmuch_database_t *notmuch,
1323 notmuch_directory_t **directory)
1325 notmuch_status_t status;
1327 if (directory == NULL)
1328 return NOTMUCH_STATUS_NULL_POINTER;
1331 /* XXX Handle read-only databases properly */
1332 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
1333 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
1336 *directory = _notmuch_directory_create (notmuch, path, NOTMUCH_FIND_CREATE, &status);
1337 } catch (const Xapian::Error &error) {
1338 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1339 error.get_msg().c_str());
1340 notmuch->exception_reported = TRUE;
1341 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1346 /* Allocate a document ID that satisfies the following criteria:
1348 * 1. The ID does not exist for any document in the Xapian database
1350 * 2. The ID was not previously returned from this function
1352 * 3. The ID is the smallest integer satisfying (1) and (2)
1354 * This function will trigger an internal error if these constraints
1355 * cannot all be satisfied, (that is, the pool of available document
1356 * IDs has been exhausted).
1359 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1361 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1363 notmuch->last_doc_id++;
1365 if (notmuch->last_doc_id == 0)
1366 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1368 return notmuch->last_doc_id;
1372 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1374 /* 16 bytes (+ terminator) for hexadecimal representation of
1375 * a 64-bit integer. */
1376 static char thread_id[17];
1377 Xapian::WritableDatabase *db;
1379 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1381 notmuch->last_thread_id++;
1383 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1385 db->set_metadata ("last_thread_id", thread_id);
1391 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1393 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1394 message_id = _message_id_compressed (ctx, message_id);
1396 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1400 /* Find the thread ID to which the message with 'message_id' belongs.
1402 * Note: 'thread_id_ret' must not be NULL!
1403 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1406 * Note: If there is no message in the database with the given
1407 * 'message_id' then a new thread_id will be allocated for this
1408 * message and stored in the database metadata, (where this same
1409 * thread ID can be looked up if the message is added to the database
1412 static notmuch_status_t
1413 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1415 const char *message_id,
1416 const char **thread_id_ret)
1418 notmuch_status_t status;
1419 notmuch_message_t *message;
1420 string thread_id_string;
1422 Xapian::WritableDatabase *db;
1424 status = notmuch_database_find_message (notmuch, message_id, &message);
1430 *thread_id_ret = talloc_steal (ctx,
1431 notmuch_message_get_thread_id (message));
1433 notmuch_message_destroy (message);
1435 return NOTMUCH_STATUS_SUCCESS;
1438 /* Message has not been seen yet.
1440 * We may have seen a reference to it already, in which case, we
1441 * can return the thread ID stored in the metadata. Otherwise, we
1442 * generate a new thread ID and store it there.
1444 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1445 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1446 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1448 if (thread_id_string.empty()) {
1449 *thread_id_ret = talloc_strdup (ctx,
1450 _notmuch_database_generate_thread_id (notmuch));
1451 db->set_metadata (metadata_key, *thread_id_ret);
1453 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1456 talloc_free (metadata_key);
1458 return NOTMUCH_STATUS_SUCCESS;
1461 static notmuch_status_t
1462 _merge_threads (notmuch_database_t *notmuch,
1463 const char *winner_thread_id,
1464 const char *loser_thread_id)
1466 Xapian::PostingIterator loser, loser_end;
1467 notmuch_message_t *message = NULL;
1468 notmuch_private_status_t private_status;
1469 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1471 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1473 for ( ; loser != loser_end; loser++) {
1474 message = _notmuch_message_create (notmuch, notmuch,
1475 *loser, &private_status);
1476 if (message == NULL) {
1477 ret = COERCE_STATUS (private_status,
1478 "Cannot find document for doc_id from query");
1482 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1483 _notmuch_message_add_term (message, "thread", winner_thread_id);
1484 _notmuch_message_sync (message);
1486 notmuch_message_destroy (message);
1492 notmuch_message_destroy (message);
1498 _my_talloc_free_for_g_hash (void *ptr)
1503 static notmuch_status_t
1504 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1505 notmuch_message_t *message,
1506 notmuch_message_file_t *message_file,
1507 const char **thread_id)
1509 GHashTable *parents = NULL;
1510 const char *refs, *in_reply_to, *in_reply_to_message_id;
1511 GList *l, *keys = NULL;
1512 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1514 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1515 _my_talloc_free_for_g_hash, NULL);
1517 refs = notmuch_message_file_get_header (message_file, "references");
1518 parse_references (message, notmuch_message_get_message_id (message),
1521 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1522 parse_references (message, notmuch_message_get_message_id (message),
1523 parents, in_reply_to);
1525 /* Carefully avoid adding any self-referential in-reply-to term. */
1526 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1527 if (in_reply_to_message_id &&
1528 strcmp (in_reply_to_message_id,
1529 notmuch_message_get_message_id (message)))
1531 _notmuch_message_add_term (message, "replyto",
1532 _parse_message_id (message, in_reply_to, NULL));
1535 keys = g_hash_table_get_keys (parents);
1536 for (l = keys; l; l = l->next) {
1537 char *parent_message_id;
1538 const char *parent_thread_id = NULL;
1540 parent_message_id = (char *) l->data;
1542 _notmuch_message_add_term (message, "reference",
1545 ret = _resolve_message_id_to_thread_id (notmuch,
1552 if (*thread_id == NULL) {
1553 *thread_id = talloc_strdup (message, parent_thread_id);
1554 _notmuch_message_add_term (message, "thread", *thread_id);
1555 } else if (strcmp (*thread_id, parent_thread_id)) {
1556 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1566 g_hash_table_unref (parents);
1571 static notmuch_status_t
1572 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1573 notmuch_message_t *message,
1574 const char **thread_id)
1576 const char *message_id = notmuch_message_get_message_id (message);
1577 Xapian::PostingIterator child, children_end;
1578 notmuch_message_t *child_message = NULL;
1579 const char *child_thread_id;
1580 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1581 notmuch_private_status_t private_status;
1583 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1585 for ( ; child != children_end; child++) {
1587 child_message = _notmuch_message_create (message, notmuch,
1588 *child, &private_status);
1589 if (child_message == NULL) {
1590 ret = COERCE_STATUS (private_status,
1591 "Cannot find document for doc_id from query");
1595 child_thread_id = notmuch_message_get_thread_id (child_message);
1596 if (*thread_id == NULL) {
1597 *thread_id = talloc_strdup (message, child_thread_id);
1598 _notmuch_message_add_term (message, "thread", *thread_id);
1599 } else if (strcmp (*thread_id, child_thread_id)) {
1600 _notmuch_message_remove_term (child_message, "reference",
1602 _notmuch_message_sync (child_message);
1603 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1608 notmuch_message_destroy (child_message);
1609 child_message = NULL;
1614 notmuch_message_destroy (child_message);
1619 /* Given a (mostly empty) 'message' and its corresponding
1620 * 'message_file' link it to existing threads in the database.
1622 * The first check is in the metadata of the database to see if we
1623 * have pre-allocated a thread_id in advance for this message, (which
1624 * would have happened if a message was previously added that
1625 * referenced this one).
1627 * Second, we look at 'message_file' and its link-relevant headers
1628 * (References and In-Reply-To) for message IDs.
1630 * Finally, we look in the database for existing message that
1631 * reference 'message'.
1633 * In all cases, we assign to the current message the first thread_id
1634 * found (through either parent or child). We will also merge any
1635 * existing, distinct threads where this message belongs to both,
1636 * (which is not uncommon when messages are processed out of order).
1638 * Finally, if no thread ID has been found through parent or child, we
1639 * call _notmuch_message_generate_thread_id to generate a new thread
1640 * ID. This should only happen for new, top-level messages, (no
1641 * References or In-Reply-To header in this message, and no previously
1642 * added message refers to this message).
1644 static notmuch_status_t
1645 _notmuch_database_link_message (notmuch_database_t *notmuch,
1646 notmuch_message_t *message,
1647 notmuch_message_file_t *message_file)
1649 notmuch_status_t status;
1650 const char *message_id, *thread_id = NULL;
1654 message_id = notmuch_message_get_message_id (message);
1655 metadata_key = _get_metadata_thread_id_key (message, message_id);
1657 /* Check if we have already seen related messages to this one.
1658 * If we have then use the thread_id that we stored at that time.
1660 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1661 if (! stored_id.empty()) {
1662 Xapian::WritableDatabase *db;
1664 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1666 /* Clear the metadata for this message ID. We don't need it
1668 db->set_metadata (metadata_key, "");
1669 thread_id = stored_id.c_str();
1671 _notmuch_message_add_term (message, "thread", thread_id);
1673 talloc_free (metadata_key);
1675 status = _notmuch_database_link_message_to_parents (notmuch, message,
1681 status = _notmuch_database_link_message_to_children (notmuch, message,
1686 /* If not part of any existing thread, generate a new thread ID. */
1687 if (thread_id == NULL) {
1688 thread_id = _notmuch_database_generate_thread_id (notmuch);
1690 _notmuch_message_add_term (message, "thread", thread_id);
1693 return NOTMUCH_STATUS_SUCCESS;
1697 notmuch_database_add_message (notmuch_database_t *notmuch,
1698 const char *filename,
1699 notmuch_message_t **message_ret)
1701 notmuch_message_file_t *message_file;
1702 notmuch_message_t *message = NULL;
1703 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1704 notmuch_private_status_t private_status;
1706 const char *date, *header;
1707 const char *from, *to, *subject;
1708 char *message_id = NULL;
1711 *message_ret = NULL;
1713 ret = _notmuch_database_ensure_writable (notmuch);
1717 message_file = notmuch_message_file_open (filename);
1718 if (message_file == NULL)
1719 return NOTMUCH_STATUS_FILE_ERROR;
1721 /* Adding a message may change many documents. Do this all
1723 ret = notmuch_database_begin_atomic (notmuch);
1727 notmuch_message_file_restrict_headers (message_file,
1738 /* Before we do any real work, (especially before doing a
1739 * potential SHA-1 computation on the entire file's contents),
1740 * let's make sure that what we're looking at looks like an
1741 * actual email message.
1743 from = notmuch_message_file_get_header (message_file, "from");
1744 subject = notmuch_message_file_get_header (message_file, "subject");
1745 to = notmuch_message_file_get_header (message_file, "to");
1747 if ((from == NULL || *from == '\0') &&
1748 (subject == NULL || *subject == '\0') &&
1749 (to == NULL || *to == '\0'))
1751 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1755 /* Now that we're sure it's mail, the first order of business
1756 * is to find a message ID (or else create one ourselves). */
1758 header = notmuch_message_file_get_header (message_file, "message-id");
1759 if (header && *header != '\0') {
1760 message_id = _parse_message_id (message_file, header, NULL);
1762 /* So the header value isn't RFC-compliant, but it's
1763 * better than no message-id at all. */
1764 if (message_id == NULL)
1765 message_id = talloc_strdup (message_file, header);
1767 /* If a message ID is too long, substitute its sha1 instead. */
1768 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1769 char *compressed = _message_id_compressed (message_file,
1771 talloc_free (message_id);
1772 message_id = compressed;
1776 if (message_id == NULL ) {
1777 /* No message-id at all, let's generate one by taking a
1778 * hash over the file's contents. */
1779 char *sha1 = notmuch_sha1_of_file (filename);
1781 /* If that failed too, something is really wrong. Give up. */
1783 ret = NOTMUCH_STATUS_FILE_ERROR;
1787 message_id = talloc_asprintf (message_file,
1788 "notmuch-sha1-%s", sha1);
1792 /* Now that we have a message ID, we get a message object,
1793 * (which may or may not reference an existing document in the
1796 message = _notmuch_message_create_for_message_id (notmuch,
1800 talloc_free (message_id);
1802 if (message == NULL) {
1803 ret = COERCE_STATUS (private_status,
1804 "Unexpected status value from _notmuch_message_create_for_message_id");
1808 _notmuch_message_add_filename (message, filename);
1810 /* Is this a newly created message object? */
1811 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1812 _notmuch_message_add_term (message, "type", "mail");
1814 ret = _notmuch_database_link_message (notmuch, message,
1819 date = notmuch_message_file_get_header (message_file, "date");
1820 _notmuch_message_set_header_values (message, date, from, subject);
1822 _notmuch_message_index_file (message, filename);
1824 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1827 _notmuch_message_sync (message);
1828 } catch (const Xapian::Error &error) {
1829 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1830 error.get_msg().c_str());
1831 notmuch->exception_reported = TRUE;
1832 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1838 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1839 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1840 *message_ret = message;
1842 notmuch_message_destroy (message);
1846 notmuch_message_file_close (message_file);
1848 ret2 = notmuch_database_end_atomic (notmuch);
1849 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1850 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
1851 ret2 != NOTMUCH_STATUS_SUCCESS)
1858 notmuch_database_remove_message (notmuch_database_t *notmuch,
1859 const char *filename)
1861 notmuch_status_t status;
1862 notmuch_message_t *message;
1864 status = notmuch_database_find_message_by_filename (notmuch, filename,
1867 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1868 status = _notmuch_message_remove_filename (message, filename);
1869 if (status == NOTMUCH_STATUS_SUCCESS)
1870 _notmuch_message_delete (message);
1871 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1872 _notmuch_message_sync (message);
1874 notmuch_message_destroy (message);
1881 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1882 const char *filename,
1883 notmuch_message_t **message_ret)
1886 const char *prefix = _find_prefix ("file-direntry");
1887 char *direntry, *term;
1888 Xapian::PostingIterator i, end;
1889 notmuch_status_t status;
1891 if (message_ret == NULL)
1892 return NOTMUCH_STATUS_NULL_POINTER;
1894 /* return NULL on any failure */
1895 *message_ret = NULL;
1897 local = talloc_new (notmuch);
1900 status = _notmuch_database_filename_to_direntry (
1901 local, notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
1905 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1907 find_doc_ids_for_term (notmuch, term, &i, &end);
1910 notmuch_private_status_t private_status;
1912 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1914 if (*message_ret == NULL)
1915 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1917 } catch (const Xapian::Error &error) {
1918 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
1919 error.get_msg().c_str());
1920 notmuch->exception_reported = TRUE;
1921 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1925 talloc_free (local);
1927 if (status && *message_ret) {
1928 notmuch_message_destroy (*message_ret);
1929 *message_ret = NULL;
1934 notmuch_string_list_t *
1935 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1936 Xapian::TermIterator &end,
1939 int prefix_len = strlen (prefix);
1940 notmuch_string_list_t *list;
1942 list = _notmuch_string_list_create (ctx);
1943 if (unlikely (list == NULL))
1946 for (i.skip_to (prefix); i != end; i++) {
1947 /* Terminate loop at first term without desired prefix. */
1948 if (strncmp ((*i).c_str (), prefix, prefix_len))
1951 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1958 notmuch_database_get_all_tags (notmuch_database_t *db)
1960 Xapian::TermIterator i, end;
1961 notmuch_string_list_t *tags;
1964 i = db->xapian_db->allterms_begin();
1965 end = db->xapian_db->allterms_end();
1966 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1967 _find_prefix ("tag"));
1968 _notmuch_string_list_sort (tags);
1969 return _notmuch_tags_create (db, tags);
1970 } catch (const Xapian::Error &error) {
1971 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1972 error.get_msg().c_str());
1973 db->exception_reported = TRUE;