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"
27 #include <glib.h> /* g_free, GPtrArray, GHashTable */
31 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
38 /* Here's the current schema for our database:
40 * We currently have two different types of documents: mail and directory.
44 * A mail document is associated with a particular email message file
45 * on disk. It is indexed with the following prefixed terms which the
46 * database uses to construct threads, etc.:
48 * Single terms of given prefix:
52 * id: Unique ID of mail, (from Message-ID header or generated
53 * as "notmuch-sha1-<sha1_sum_of_entire_file>.
55 * thread: The ID of the thread to which the mail belongs
57 * replyto: The ID from the In-Reply-To header of the mail (if any).
59 * Multiple terms of given prefix:
61 * reference: All message IDs from In-Reply-To and Re ferences
62 * headers in the message.
64 * tag: Any tags associated with this message by the user.
66 * file-direntry: A colon-separated pair of values
67 * (INTEGER:STRING), where INTEGER is the
68 * document ID of a directory document, and
69 * STRING is the name of a file within that
70 * directory for this mail message.
72 * A mail document also has two values:
74 * TIMESTAMP: The time_t value corresponding to the message's
77 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
79 * In addition, terms from the content of the message are added with
80 * "from", "to", "attachment", and "subject" prefixes for use by the
81 * user in searching. But the database doesn't really care itself
84 * The data portion of a mail document is empty.
88 * A directory document is used by a client of the notmuch library to
89 * maintain data necessary to allow for efficient polling of mail
92 * All directory documents contain one term:
94 * directory: The directory path (relative to the database path)
95 * Or the SHA1 sum of the directory path (if the
96 * path itself is too long to fit in a Xapian
99 * And all directory documents for directories other than top-level
100 * directories also contain the following term:
102 * directory-direntry: A colon-separated pair of values
103 * (INTEGER:STRING), where INTEGER is the
104 * document ID of the parent directory
105 * document, and STRING is the name of this
106 * directory within that parent.
108 * All directory documents have a single value:
110 * TIMESTAMP: The mtime of the directory (at last scan)
112 * The data portion of a directory document contains the path of the
113 * directory (relative to the database path).
116 /* With these prefix values we follow the conventions published here:
118 * http://xapian.org/docs/omega/termprefixes.html
120 * as much as makes sense. Note that I took some liberty in matching
121 * the reserved prefix values to notmuch concepts, (for example, 'G'
122 * is documented as "newsGroup (or similar entity - e.g. a web forum
123 * name)", for which I think the thread is the closest analogue in
124 * notmuch. This in spite of the fact that we will eventually be
125 * storing mailing-list messages where 'G' for "mailing list name"
126 * might be even a closer analogue. I'm treating the single-character
127 * prefixes preferentially for core notmuch concepts (which will be
128 * nearly universal to all mail messages).
131 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
133 { "reference", "XREFERENCE" },
134 { "replyto", "XREPLYTO" },
135 { "directory", "XDIRECTORY" },
136 { "file-direntry", "XFDIRENTRY" },
137 { "directory-direntry", "XDDIRENTRY" },
140 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
146 prefix_t PROBABILISTIC_PREFIX[]= {
149 { "attachment", "XATTACHMENT" },
150 { "subject", "XSUBJECT"}
154 _internal_error (const char *format, ...)
158 va_start (va_args, format);
160 fprintf (stderr, "Internal error: ");
161 vfprintf (stderr, format, va_args);
169 _find_prefix (const char *name)
173 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
174 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
175 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
178 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
179 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
180 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
183 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
184 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
185 return PROBABILISTIC_PREFIX[i].prefix;
188 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
194 notmuch_status_to_string (notmuch_status_t status)
197 case NOTMUCH_STATUS_SUCCESS:
198 return "No error occurred";
199 case NOTMUCH_STATUS_OUT_OF_MEMORY:
200 return "Out of memory";
201 case NOTMUCH_STATUS_READONLY_DATABASE:
202 return "Attempt to write to a read-only database";
203 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
204 return "A Xapian exception occurred";
205 case NOTMUCH_STATUS_FILE_ERROR:
206 return "Something went wrong trying to read or write a file";
207 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
208 return "File is not an email";
209 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
210 return "Message ID is identical to a message in database";
211 case NOTMUCH_STATUS_NULL_POINTER:
212 return "Erroneous NULL pointer";
213 case NOTMUCH_STATUS_TAG_TOO_LONG:
214 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
215 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
216 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
218 case NOTMUCH_STATUS_LAST_STATUS:
219 return "Unknown error status value";
224 find_doc_ids_for_term (notmuch_database_t *notmuch,
226 Xapian::PostingIterator *begin,
227 Xapian::PostingIterator *end)
229 *begin = notmuch->xapian_db->postlist_begin (term);
231 *end = notmuch->xapian_db->postlist_end (term);
235 find_doc_ids (notmuch_database_t *notmuch,
236 const char *prefix_name,
238 Xapian::PostingIterator *begin,
239 Xapian::PostingIterator *end)
243 term = talloc_asprintf (notmuch, "%s%s",
244 _find_prefix (prefix_name), value);
246 find_doc_ids_for_term (notmuch, term, begin, end);
251 notmuch_private_status_t
252 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
253 const char *prefix_name,
255 unsigned int *doc_id)
257 Xapian::PostingIterator i, end;
259 find_doc_ids (notmuch, prefix_name, value, &i, &end);
263 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
268 #if DEBUG_DATABASE_SANITY
272 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
276 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
279 static Xapian::Document
280 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
282 return notmuch->xapian_db->get_document (doc_id);
286 notmuch_database_find_message (notmuch_database_t *notmuch,
287 const char *message_id)
289 notmuch_private_status_t status;
292 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
293 message_id, &doc_id);
295 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
298 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
301 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
302 * a (potentially nested) parenthesized sequence with '\' used to
303 * escape any character (including parentheses).
305 * If the sequence to be skipped continues to the end of the string,
306 * then 'str' will be left pointing at the final terminating '\0'
310 skip_space_and_comments (const char **str)
315 while (*s && (isspace (*s) || *s == '(')) {
316 while (*s && isspace (*s))
321 while (*s && nesting) {
324 } else if (*s == ')') {
326 } else if (*s == '\\') {
338 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
339 * comments, and the '<' and '>' delimeters.
341 * If not NULL, then *next will be made to point to the first character
342 * not parsed, (possibly pointing to the final '\0' terminator.
344 * Returns a newly talloc'ed string belonging to 'ctx'.
346 * Returns NULL if there is any error parsing the message-id. */
348 _parse_message_id (void *ctx, const char *message_id, const char **next)
353 if (message_id == NULL || *message_id == '\0')
358 skip_space_and_comments (&s);
360 /* Skip any unstructured text as well. */
361 while (*s && *s != '<')
372 skip_space_and_comments (&s);
375 while (*end && *end != '>')
384 if (end > s && *end == '>')
389 result = talloc_strndup (ctx, s, end - s + 1);
391 /* Finally, collapse any whitespace that is within the message-id
397 for (r = result, len = strlen (r); *r; r++, len--)
398 if (*r == ' ' || *r == '\t')
399 memmove (r, r+1, len);
405 /* Parse a References header value, putting a (talloc'ed under 'ctx')
406 * copy of each referenced message-id into 'hash'.
408 * We explicitly avoid including any reference identical to
409 * 'message_id' in the result (to avoid mass confusion when a single
410 * message references itself cyclically---and yes, mail messages are
411 * not infrequent in the wild that do this---don't ask me why).
414 parse_references (void *ctx,
415 const char *message_id,
421 if (refs == NULL || *refs == '\0')
425 ref = _parse_message_id (ctx, refs, &refs);
427 if (ref && strcmp (ref, message_id))
428 g_hash_table_insert (hash, ref, NULL);
433 notmuch_database_create (const char *path)
435 notmuch_database_t *notmuch = NULL;
436 char *notmuch_path = NULL;
441 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
445 err = stat (path, &st);
447 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
448 path, strerror (errno));
452 if (! S_ISDIR (st.st_mode)) {
453 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
458 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
460 err = mkdir (notmuch_path, 0755);
463 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
464 notmuch_path, strerror (errno));
468 notmuch = notmuch_database_open (path,
469 NOTMUCH_DATABASE_MODE_READ_WRITE);
473 talloc_free (notmuch_path);
479 notmuch_database_open (const char *path,
480 notmuch_database_mode_t mode)
482 notmuch_database_t *notmuch = NULL;
483 char *notmuch_path = NULL, *xapian_path = NULL;
488 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
490 fprintf (stderr, "Out of memory\n");
494 err = stat (notmuch_path, &st);
496 fprintf (stderr, "Error opening database at %s: %s\n",
497 notmuch_path, strerror (errno));
501 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
503 fprintf (stderr, "Out of memory\n");
507 notmuch = talloc (NULL, notmuch_database_t);
508 notmuch->exception_reported = FALSE;
509 notmuch->path = talloc_strdup (notmuch, path);
511 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
512 notmuch->path[strlen (notmuch->path) - 1] = '\0';
514 notmuch->mode = mode;
516 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
517 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
518 Xapian::DB_CREATE_OR_OPEN);
520 notmuch->xapian_db = new Xapian::Database (xapian_path);
522 notmuch->query_parser = new Xapian::QueryParser;
523 notmuch->term_gen = new Xapian::TermGenerator;
524 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
525 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
527 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
528 notmuch->query_parser->set_database (*notmuch->xapian_db);
529 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
530 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
531 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
533 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
534 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
535 notmuch->query_parser->add_boolean_prefix (prefix->name,
539 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
540 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
541 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
543 } catch (const Xapian::Error &error) {
544 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
545 error.get_msg().c_str());
559 notmuch_database_close (notmuch_database_t *notmuch)
562 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
563 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
564 } catch (const Xapian::Error &error) {
565 if (! notmuch->exception_reported) {
566 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
567 error.get_msg().c_str());
571 delete notmuch->term_gen;
572 delete notmuch->query_parser;
573 delete notmuch->xapian_db;
574 delete notmuch->value_range_processor;
575 talloc_free (notmuch);
579 notmuch_database_get_path (notmuch_database_t *notmuch)
581 return notmuch->path;
584 /* We allow the user to use arbitrarily long paths for directories. But
585 * we have a term-length limit. So if we exceed that, we'll use the
586 * SHA-1 of the path for the database term.
588 * Note: This function may return the original value of 'path'. If it
589 * does not, then the caller is responsible to free() the returned
593 _notmuch_database_get_directory_db_path (const char *path)
595 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
597 if (term_len > NOTMUCH_TERM_MAX)
598 return notmuch_sha1_of_string (path);
603 /* Given a path, split it into two parts: the directory part is all
604 * components except for the last, and the basename is that last
605 * component. Getting the return-value for either part is optional
606 * (the caller can pass NULL).
608 * The original 'path' can represent either a regular file or a
609 * directory---the splitting will be carried out in the same way in
610 * either case. Trailing slashes on 'path' will be ignored, and any
611 * cases of multiple '/' characters appearing in series will be
612 * treated as a single '/'.
614 * Allocation (if any) will have 'ctx' as the talloc owner. But
615 * pointers will be returned within the original path string whenever
618 * Note: If 'path' is non-empty and contains no non-trailing slash,
619 * (that is, consists of a filename with no parent directory), then
620 * the directory returned will be an empty string. However, if 'path'
621 * is an empty string, then both directory and basename will be
625 _notmuch_database_split_path (void *ctx,
627 const char **directory,
628 const char **basename)
632 if (path == NULL || *path == '\0') {
637 return NOTMUCH_STATUS_SUCCESS;
640 /* Find the last slash (not counting a trailing slash), if any. */
642 slash = path + strlen (path) - 1;
644 /* First, skip trailing slashes. */
645 while (slash != path) {
652 /* Then, find a slash. */
653 while (slash != path) {
663 /* Finally, skip multiple slashes. */
664 while (slash != path) {
673 *directory = talloc_strdup (ctx, "");
678 *directory = talloc_strndup (ctx, path, slash - path + 1);
681 return NOTMUCH_STATUS_SUCCESS;
685 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
687 unsigned int *directory_id)
689 notmuch_directory_t *directory;
690 notmuch_status_t status;
694 return NOTMUCH_STATUS_SUCCESS;
697 directory = _notmuch_directory_create (notmuch, path, &status);
703 *directory_id = _notmuch_directory_get_document_id (directory);
705 notmuch_directory_destroy (directory);
707 return NOTMUCH_STATUS_SUCCESS;
711 _notmuch_database_get_directory_path (void *ctx,
712 notmuch_database_t *notmuch,
715 Xapian::Document document;
717 document = find_document_for_doc_id (notmuch, doc_id);
719 return talloc_strdup (ctx, document.get_data ().c_str ());
722 /* Given a legal 'filename' for the database, (either relative to
723 * database path or absolute with initial components identical to
724 * database path), return a new string (with 'ctx' as the talloc
725 * owner) suitable for use as a direntry term value.
728 _notmuch_database_filename_to_direntry (void *ctx,
729 notmuch_database_t *notmuch,
730 const char *filename,
733 const char *relative, *directory, *basename;
734 Xapian::docid directory_id;
735 notmuch_status_t status;
737 relative = _notmuch_database_relative_path (notmuch, filename);
739 status = _notmuch_database_split_path (ctx, relative,
740 &directory, &basename);
744 status = _notmuch_database_find_directory_id (notmuch, directory,
749 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
751 return NOTMUCH_STATUS_SUCCESS;
754 /* Given a legal 'path' for the database, return the relative path.
756 * The return value will be a pointer to the originl path contents,
757 * and will be either the original string (if 'path' was relative) or
758 * a portion of the string (if path was absolute and begins with the
762 _notmuch_database_relative_path (notmuch_database_t *notmuch,
765 const char *db_path, *relative;
766 unsigned int db_path_len;
768 db_path = notmuch_database_get_path (notmuch);
769 db_path_len = strlen (db_path);
773 if (*relative == '/') {
774 while (*relative == '/' && *(relative+1) == '/')
777 if (strncmp (relative, db_path, db_path_len) == 0)
779 relative += db_path_len;
780 while (*relative == '/')
788 notmuch_directory_t *
789 notmuch_database_get_directory (notmuch_database_t *notmuch,
792 notmuch_status_t status;
794 return _notmuch_directory_create (notmuch, path, &status);
797 /* Find the thread ID to which the message with 'message_id' belongs.
799 * Returns NULL if no message with message ID 'message_id' is in the
802 * Otherwise, returns a newly talloced string belonging to 'ctx'.
805 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
807 const char *message_id)
809 notmuch_message_t *message;
810 const char *ret = NULL;
812 message = notmuch_database_find_message (notmuch, message_id);
816 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
820 notmuch_message_destroy (message);
825 static notmuch_status_t
826 _merge_threads (notmuch_database_t *notmuch,
827 const char *winner_thread_id,
828 const char *loser_thread_id)
830 Xapian::PostingIterator loser, loser_end;
831 notmuch_message_t *message = NULL;
832 notmuch_private_status_t private_status;
833 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
835 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
837 for ( ; loser != loser_end; loser++) {
838 message = _notmuch_message_create (notmuch, notmuch,
839 *loser, &private_status);
840 if (message == NULL) {
841 ret = COERCE_STATUS (private_status,
842 "Cannot find document for doc_id from query");
846 _notmuch_message_remove_term (message, "thread", loser_thread_id);
847 _notmuch_message_add_term (message, "thread", winner_thread_id);
848 _notmuch_message_sync (message);
850 notmuch_message_destroy (message);
856 notmuch_message_destroy (message);
862 _my_talloc_free_for_g_hash (void *ptr)
867 static notmuch_status_t
868 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
869 notmuch_message_t *message,
870 notmuch_message_file_t *message_file,
871 const char **thread_id)
873 GHashTable *parents = NULL;
874 const char *refs, *in_reply_to, *in_reply_to_message_id;
875 GList *l, *keys = NULL;
876 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
878 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
879 _my_talloc_free_for_g_hash, NULL);
881 refs = notmuch_message_file_get_header (message_file, "references");
882 parse_references (message, notmuch_message_get_message_id (message),
885 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
886 parse_references (message, notmuch_message_get_message_id (message),
887 parents, in_reply_to);
889 /* Carefully avoid adding any self-referential in-reply-to term. */
890 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
891 if (in_reply_to_message_id &&
892 strcmp (in_reply_to_message_id,
893 notmuch_message_get_message_id (message)))
895 _notmuch_message_add_term (message, "replyto",
896 _parse_message_id (message, in_reply_to, NULL));
899 keys = g_hash_table_get_keys (parents);
900 for (l = keys; l; l = l->next) {
901 char *parent_message_id;
902 const char *parent_thread_id;
904 parent_message_id = (char *) l->data;
905 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
909 if (parent_thread_id == NULL) {
910 _notmuch_message_add_term (message, "reference",
913 if (*thread_id == NULL) {
914 *thread_id = talloc_strdup (message, parent_thread_id);
915 _notmuch_message_add_term (message, "thread", *thread_id);
916 } else if (strcmp (*thread_id, parent_thread_id)) {
917 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
928 g_hash_table_unref (parents);
933 static notmuch_status_t
934 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
935 notmuch_message_t *message,
936 const char **thread_id)
938 const char *message_id = notmuch_message_get_message_id (message);
939 Xapian::PostingIterator child, children_end;
940 notmuch_message_t *child_message = NULL;
941 const char *child_thread_id;
942 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
943 notmuch_private_status_t private_status;
945 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
947 for ( ; child != children_end; child++) {
949 child_message = _notmuch_message_create (message, notmuch,
950 *child, &private_status);
951 if (child_message == NULL) {
952 ret = COERCE_STATUS (private_status,
953 "Cannot find document for doc_id from query");
957 child_thread_id = notmuch_message_get_thread_id (child_message);
958 if (*thread_id == NULL) {
959 *thread_id = talloc_strdup (message, child_thread_id);
960 _notmuch_message_add_term (message, "thread", *thread_id);
961 } else if (strcmp (*thread_id, child_thread_id)) {
962 _notmuch_message_remove_term (child_message, "reference",
964 _notmuch_message_sync (child_message);
965 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
970 notmuch_message_destroy (child_message);
971 child_message = NULL;
976 notmuch_message_destroy (child_message);
981 /* Given a (mostly empty) 'message' and its corresponding
982 * 'message_file' link it to existing threads in the database.
984 * We first look at 'message_file' and its link-relevant headers
985 * (References and In-Reply-To) for message IDs. We also look in the
986 * database for existing message that reference 'message'.
988 * The end result is to call _notmuch_message_ensure_thread_id which
989 * generates a new thread ID if the message doesn't connect to any
992 static notmuch_status_t
993 _notmuch_database_link_message (notmuch_database_t *notmuch,
994 notmuch_message_t *message,
995 notmuch_message_file_t *message_file)
997 notmuch_status_t status;
998 const char *thread_id = NULL;
1000 status = _notmuch_database_link_message_to_parents (notmuch, message,
1006 status = _notmuch_database_link_message_to_children (notmuch, message,
1011 if (thread_id == NULL)
1012 _notmuch_message_ensure_thread_id (message);
1014 return NOTMUCH_STATUS_SUCCESS;
1018 notmuch_database_add_message (notmuch_database_t *notmuch,
1019 const char *filename,
1020 notmuch_message_t **message_ret)
1022 notmuch_message_file_t *message_file;
1023 notmuch_message_t *message = NULL;
1024 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1025 notmuch_private_status_t private_status;
1027 const char *date, *header;
1028 const char *from, *to, *subject;
1029 char *message_id = NULL;
1032 *message_ret = NULL;
1034 message_file = notmuch_message_file_open (filename);
1035 if (message_file == NULL) {
1036 ret = NOTMUCH_STATUS_FILE_ERROR;
1040 notmuch_message_file_restrict_headers (message_file,
1051 /* Before we do any real work, (especially before doing a
1052 * potential SHA-1 computation on the entire file's contents),
1053 * let's make sure that what we're looking at looks like an
1054 * actual email message.
1056 from = notmuch_message_file_get_header (message_file, "from");
1057 subject = notmuch_message_file_get_header (message_file, "subject");
1058 to = notmuch_message_file_get_header (message_file, "to");
1060 if ((from == NULL || *from == '\0') &&
1061 (subject == NULL || *subject == '\0') &&
1062 (to == NULL || *to == '\0'))
1064 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1068 /* Now that we're sure it's mail, the first order of business
1069 * is to find a message ID (or else create one ourselves). */
1071 header = notmuch_message_file_get_header (message_file, "message-id");
1072 if (header && *header != '\0') {
1073 message_id = _parse_message_id (message_file, header, NULL);
1075 /* So the header value isn't RFC-compliant, but it's
1076 * better than no message-id at all. */
1077 if (message_id == NULL)
1078 message_id = talloc_strdup (message_file, header);
1080 /* Reject a Message ID that's too long. */
1081 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1082 talloc_free (message_id);
1087 if (message_id == NULL ) {
1088 /* No message-id at all, let's generate one by taking a
1089 * hash over the file's contents. */
1090 char *sha1 = notmuch_sha1_of_file (filename);
1092 /* If that failed too, something is really wrong. Give up. */
1094 ret = NOTMUCH_STATUS_FILE_ERROR;
1098 message_id = talloc_asprintf (message_file,
1099 "notmuch-sha1-%s", sha1);
1103 /* Now that we have a message ID, we get a message object,
1104 * (which may or may not reference an existing document in the
1107 message = _notmuch_message_create_for_message_id (notmuch,
1111 talloc_free (message_id);
1113 if (message == NULL) {
1114 ret = COERCE_STATUS (private_status,
1115 "Unexpected status value from _notmuch_message_create_for_message_id");
1119 _notmuch_message_add_filename (message, filename);
1121 /* Is this a newly created message object? */
1122 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1123 _notmuch_message_add_term (message, "type", "mail");
1125 ret = _notmuch_database_link_message (notmuch, message,
1130 date = notmuch_message_file_get_header (message_file, "date");
1131 _notmuch_message_set_date (message, date);
1133 _notmuch_message_index_file (message, filename);
1135 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1138 _notmuch_message_sync (message);
1139 } catch (const Xapian::Error &error) {
1140 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1141 error.get_description().c_str());
1142 notmuch->exception_reported = TRUE;
1143 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1149 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1150 *message_ret = message;
1152 notmuch_message_destroy (message);
1156 notmuch_message_file_close (message_file);
1162 notmuch_database_remove_message (notmuch_database_t *notmuch,
1163 const char *filename)
1165 Xapian::WritableDatabase *db;
1166 void *local = talloc_new (notmuch);
1167 const char *prefix = _find_prefix ("file-direntry");
1168 char *direntry, *term;
1169 Xapian::PostingIterator i, end;
1170 Xapian::Document document;
1171 notmuch_status_t status;
1173 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
1174 fprintf (stderr, "Attempted to update a read-only database.\n");
1175 return NOTMUCH_STATUS_READONLY_DATABASE;
1178 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1180 status = _notmuch_database_filename_to_direntry (local, notmuch,
1181 filename, &direntry);
1185 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1187 find_doc_ids_for_term (notmuch, term, &i, &end);
1189 for ( ; i != end; i++) {
1190 Xapian::TermIterator j;
1192 document = find_document_for_doc_id (notmuch, *i);
1194 document.remove_term (term);
1196 j = document.termlist_begin ();
1199 /* Was this the last file-direntry in the message? */
1200 if (j == document.termlist_end () ||
1201 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1203 db->delete_document (document.get_docid ());
1205 db->replace_document (document.get_docid (), document);
1209 talloc_free (local);
1211 return NOTMUCH_STATUS_SUCCESS;
1215 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1216 Xapian::TermIterator &end)
1218 const char *prefix = _find_prefix ("tag");
1219 notmuch_tags_t *tags;
1222 /* Currently this iteration is written with the assumption that
1223 * "tag" has a single-character prefix. */
1224 assert (strlen (prefix) == 1);
1226 tags = _notmuch_tags_create (ctx);
1227 if (unlikely (tags == NULL))
1235 if (tag.empty () || tag[0] != *prefix)
1238 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1243 _notmuch_tags_prepare_iterator (tags);
1249 notmuch_database_get_all_tags (notmuch_database_t *db)
1251 Xapian::TermIterator i, end;
1252 i = db->xapian_db->allterms_begin();
1253 end = db->xapian_db->allterms_end();
1254 return _notmuch_convert_tags(db, i, end);