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"
22 #include "parse-time-vrp.h"
23 #include "string-util.h"
32 #include <glib.h> /* g_free, GPtrArray, GHashTable */
33 #include <glib-object.h> /* g_type_init */
35 #include <gmime/gmime.h> /* g_mime_init */
39 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46 #define NOTMUCH_DATABASE_VERSION 3
48 #define STRINGIFY(s) _SUB_STRINGIFY(s)
49 #define _SUB_STRINGIFY(s) #s
51 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
53 * We currently have two different types of documents (mail and
54 * directory) and also some metadata.
58 * A mail document is associated with a particular email message. It
59 * is stored in one or more files on disk (though only one has its
60 * content indexed) and is uniquely identified by its "id" field
61 * (which is generally the message ID). It is indexed with the
62 * following prefixed terms which the database uses to construct
65 * Single terms of given prefix:
69 * id: Unique ID of mail. This is from the Message-ID header
70 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
71 * If it's present and too long, then we use
72 * "notmuch-sha1-<sha1_sum_of_message_id>".
73 * If this header is not present, we use
74 * "notmuch-sha1-<sha1_sum_of_entire_file>".
76 * thread: The ID of the thread to which the mail belongs
78 * replyto: The ID from the In-Reply-To header of the mail (if any).
80 * Multiple terms of given prefix:
82 * reference: All message IDs from In-Reply-To and References
83 * headers in the message.
85 * tag: Any tags associated with this message by the user.
87 * file-direntry: A colon-separated pair of values
88 * (INTEGER:STRING), where INTEGER is the
89 * document ID of a directory document, and
90 * STRING is the name of a file within that
91 * directory for this mail message.
93 * A mail document also has four values:
95 * TIMESTAMP: The time_t value corresponding to the message's
98 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
100 * FROM: The value of the "From" header
102 * SUBJECT: The value of the "Subject" header
104 * In addition, terms from the content of the message are added with
105 * "from", "to", "attachment", and "subject" prefixes for use by the
106 * user in searching. Similarly, terms from the path of the mail
107 * message are added with "folder" and "path" prefixes. But the
108 * database doesn't really care itself about any of these.
110 * The data portion of a mail document is empty.
114 * A directory document is used by a client of the notmuch library to
115 * maintain data necessary to allow for efficient polling of mail
118 * All directory documents contain one term:
120 * directory: The directory path (relative to the database path)
121 * Or the SHA1 sum of the directory path (if the
122 * path itself is too long to fit in a Xapian
125 * And all directory documents for directories other than top-level
126 * directories also contain the following term:
128 * directory-direntry: A colon-separated pair of values
129 * (INTEGER:STRING), where INTEGER is the
130 * document ID of the parent directory
131 * document, and STRING is the name of this
132 * directory within that parent.
134 * All directory documents have a single value:
136 * TIMESTAMP: The mtime of the directory (at last scan)
138 * The data portion of a directory document contains the path of the
139 * directory (relative to the database path).
143 * Xapian allows us to store arbitrary name-value pairs as
144 * "metadata". We currently use the following metadata names with the
147 * version The database schema version, (which is distinct
148 * from both the notmuch package version (see
149 * notmuch --version) and the libnotmuch library
150 * version. The version is stored as an base-10
151 * ASCII integer. The initial database version
152 * was 1, (though a schema existed before that
153 * were no "version" database value existed at
154 * all). Successive versions are allocated as
155 * changes are made to the database (such as by
156 * indexing new fields).
158 * features The set of features supported by this
159 * database. This consists of a set of
160 * '\n'-separated lines, where each is a feature
161 * name, a '\t', and compatibility flags. If the
162 * compatibility flags contain 'w', then the
163 * opener must support this feature to safely
164 * write this database. If the compatibility
165 * flags contain 'r', then the opener must
166 * support this feature to read this database.
167 * Introduced in database version 3.
169 * last_thread_id The last thread ID generated. This is stored
170 * as a 16-byte hexadecimal ASCII representation
171 * of a 64-bit unsigned integer. The first ID
172 * generated is 1 and the value will be
173 * incremented for each thread ID.
175 * thread_id_* A pre-allocated thread ID for a particular
176 * message. This is actually an arbitrarily large
177 * family of metadata name. Any particular name is
178 * formed by concatenating "thread_id_" with a message
179 * ID (or the SHA1 sum of a message ID if it is very
180 * long---see description of 'id' in the mail
181 * document). The value stored is a thread ID.
183 * These thread ID metadata values are stored
184 * whenever a message references a parent message
185 * that does not yet exist in the database. A
186 * thread ID will be allocated and stored, and if
187 * the message is later added, the stored thread
188 * ID will be used (and the metadata value will
191 * Even before a message is added, it's
192 * pre-allocated thread ID is useful so that all
193 * descendant messages that reference this common
194 * parent can be recognized as belonging to the
198 /* With these prefix values we follow the conventions published here:
200 * http://xapian.org/docs/omega/termprefixes.html
202 * as much as makes sense. Note that I took some liberty in matching
203 * the reserved prefix values to notmuch concepts, (for example, 'G'
204 * is documented as "newsGroup (or similar entity - e.g. a web forum
205 * name)", for which I think the thread is the closest analogue in
206 * notmuch. This in spite of the fact that we will eventually be
207 * storing mailing-list messages where 'G' for "mailing list name"
208 * might be even a closer analogue. I'm treating the single-character
209 * prefixes preferentially for core notmuch concepts (which will be
210 * nearly universal to all mail messages).
213 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
215 { "reference", "XREFERENCE" },
216 { "replyto", "XREPLYTO" },
217 { "directory", "XDIRECTORY" },
218 { "file-direntry", "XFDIRENTRY" },
219 { "directory-direntry", "XDDIRENTRY" },
222 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
229 * Without the ":", since this is a multi-letter prefix, Xapian
230 * will add a colon itself if the first letter of the path is
231 * upper-case ASCII. Including the ":" forces there to always be a
232 * colon, which keeps our own logic simpler.
234 { "folder", "XFOLDER:" },
237 static prefix_t PROBABILISTIC_PREFIX[]= {
240 { "attachment", "XATTACHMENT" },
241 { "subject", "XSUBJECT"},
245 _find_prefix (const char *name)
249 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
250 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
251 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
254 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
255 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
256 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
259 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
260 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
261 return PROBABILISTIC_PREFIX[i].prefix;
264 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
269 static const struct {
270 /* NOTMUCH_FEATURE_* value. */
271 _notmuch_features value;
272 /* Feature name as it appears in the database. This name should
273 * be appropriate for displaying to the user if an older version
274 * of notmuch doesn't support this feature. */
276 /* Compatibility flags when this feature is declared. */
278 } feature_names[] = {
279 { NOTMUCH_FEATURE_FILE_TERMS,
280 "multiple paths per message", "rw" },
281 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
282 "relative directory paths", "rw" },
283 /* Header values are not required for reading a database because a
284 * reader can just refer to the message file. */
285 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
286 "from/subject/message-ID in database", "w" },
287 { NOTMUCH_FEATURE_BOOL_FOLDER,
288 "exact folder:/path: search", "rw" },
292 notmuch_status_to_string (notmuch_status_t status)
295 case NOTMUCH_STATUS_SUCCESS:
296 return "No error occurred";
297 case NOTMUCH_STATUS_OUT_OF_MEMORY:
298 return "Out of memory";
299 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
300 return "Attempt to write to a read-only database";
301 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
302 return "A Xapian exception occurred";
303 case NOTMUCH_STATUS_FILE_ERROR:
304 return "Something went wrong trying to read or write a file";
305 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
306 return "File is not an email";
307 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
308 return "Message ID is identical to a message in database";
309 case NOTMUCH_STATUS_NULL_POINTER:
310 return "Erroneous NULL pointer";
311 case NOTMUCH_STATUS_TAG_TOO_LONG:
312 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
313 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
314 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
315 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
316 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
317 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
318 return "Unsupported operation";
319 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
320 return "Operation requires a database upgrade";
322 case NOTMUCH_STATUS_LAST_STATUS:
323 return "Unknown error status value";
328 find_doc_ids_for_term (notmuch_database_t *notmuch,
330 Xapian::PostingIterator *begin,
331 Xapian::PostingIterator *end)
333 *begin = notmuch->xapian_db->postlist_begin (term);
335 *end = notmuch->xapian_db->postlist_end (term);
339 find_doc_ids (notmuch_database_t *notmuch,
340 const char *prefix_name,
342 Xapian::PostingIterator *begin,
343 Xapian::PostingIterator *end)
347 term = talloc_asprintf (notmuch, "%s%s",
348 _find_prefix (prefix_name), value);
350 find_doc_ids_for_term (notmuch, term, begin, end);
355 notmuch_private_status_t
356 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
357 const char *prefix_name,
359 unsigned int *doc_id)
361 Xapian::PostingIterator i, end;
363 find_doc_ids (notmuch, prefix_name, value, &i, &end);
367 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
372 #if DEBUG_DATABASE_SANITY
376 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
380 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
383 static Xapian::Document
384 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
386 return notmuch->xapian_db->get_document (doc_id);
389 /* Generate a compressed version of 'message_id' of the form:
391 * notmuch-sha1-<sha1_sum_of_message_id>
394 _message_id_compressed (void *ctx, const char *message_id)
396 char *sha1, *compressed;
398 sha1 = _notmuch_sha1_of_string (message_id);
400 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
407 notmuch_database_find_message (notmuch_database_t *notmuch,
408 const char *message_id,
409 notmuch_message_t **message_ret)
411 notmuch_private_status_t status;
414 if (message_ret == NULL)
415 return NOTMUCH_STATUS_NULL_POINTER;
417 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
418 message_id = _message_id_compressed (notmuch, message_id);
421 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
422 message_id, &doc_id);
424 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
427 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
429 if (*message_ret == NULL)
430 return NOTMUCH_STATUS_OUT_OF_MEMORY;
433 return NOTMUCH_STATUS_SUCCESS;
434 } catch (const Xapian::Error &error) {
435 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
436 error.get_msg().c_str());
437 notmuch->exception_reported = TRUE;
439 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
443 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
444 * a (potentially nested) parenthesized sequence with '\' used to
445 * escape any character (including parentheses).
447 * If the sequence to be skipped continues to the end of the string,
448 * then 'str' will be left pointing at the final terminating '\0'
452 skip_space_and_comments (const char **str)
457 while (*s && (isspace (*s) || *s == '(')) {
458 while (*s && isspace (*s))
463 while (*s && nesting) {
466 } else if (*s == ')') {
468 } else if (*s == '\\') {
480 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
481 * comments, and the '<' and '>' delimiters.
483 * If not NULL, then *next will be made to point to the first character
484 * not parsed, (possibly pointing to the final '\0' terminator.
486 * Returns a newly talloc'ed string belonging to 'ctx'.
488 * Returns NULL if there is any error parsing the message-id. */
490 _parse_message_id (void *ctx, const char *message_id, const char **next)
495 if (message_id == NULL || *message_id == '\0')
500 skip_space_and_comments (&s);
502 /* Skip any unstructured text as well. */
503 while (*s && *s != '<')
514 skip_space_and_comments (&s);
517 while (*end && *end != '>')
526 if (end > s && *end == '>')
531 result = talloc_strndup (ctx, s, end - s + 1);
533 /* Finally, collapse any whitespace that is within the message-id
539 for (r = result, len = strlen (r); *r; r++, len--)
540 if (*r == ' ' || *r == '\t')
541 memmove (r, r+1, len);
547 /* Parse a References header value, putting a (talloc'ed under 'ctx')
548 * copy of each referenced message-id into 'hash'.
550 * We explicitly avoid including any reference identical to
551 * 'message_id' in the result (to avoid mass confusion when a single
552 * message references itself cyclically---and yes, mail messages are
553 * not infrequent in the wild that do this---don't ask me why).
555 * Return the last reference parsed, if it is not equal to message_id.
558 parse_references (void *ctx,
559 const char *message_id,
563 char *ref, *last_ref = NULL;
565 if (refs == NULL || *refs == '\0')
569 ref = _parse_message_id (ctx, refs, &refs);
571 if (ref && strcmp (ref, message_id)) {
572 g_hash_table_insert (hash, ref, NULL);
577 /* The return value of this function is used to add a parent
578 * reference to the database. We should avoid making a message
579 * its own parent, thus the above check.
585 notmuch_database_create (const char *path, notmuch_database_t **database)
587 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
588 notmuch_database_t *notmuch = NULL;
589 char *notmuch_path = NULL;
594 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
595 status = NOTMUCH_STATUS_NULL_POINTER;
599 err = stat (path, &st);
601 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
602 path, strerror (errno));
603 status = NOTMUCH_STATUS_FILE_ERROR;
607 if (! S_ISDIR (st.st_mode)) {
608 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
610 status = NOTMUCH_STATUS_FILE_ERROR;
614 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
616 err = mkdir (notmuch_path, 0755);
619 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
620 notmuch_path, strerror (errno));
621 status = NOTMUCH_STATUS_FILE_ERROR;
625 status = notmuch_database_open (path,
626 NOTMUCH_DATABASE_MODE_READ_WRITE,
631 /* Upgrade doesn't add this feature to existing databases, but new
632 * databases have it. */
633 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
635 status = notmuch_database_upgrade (notmuch, NULL, NULL);
637 notmuch_database_close(notmuch);
643 talloc_free (notmuch_path);
648 talloc_free (notmuch);
653 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
655 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
656 fprintf (stderr, "Cannot write to a read-only database.\n");
657 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
660 return NOTMUCH_STATUS_SUCCESS;
663 /* Parse a database features string from the given database version.
664 * Returns the feature bit set.
666 * For version < 3, this ignores the features string and returns a
667 * hard-coded set of features.
669 * If there are unrecognized features that are required to open the
670 * database in mode (which should be 'r' or 'w'), return a
671 * comma-separated list of unrecognized but required features in
672 * *incompat_out suitable for presenting to the user. *incompat_out
673 * will be allocated from ctx.
675 static _notmuch_features
676 _parse_features (const void *ctx, const char *features, unsigned int version,
677 char mode, char **incompat_out)
679 _notmuch_features res = static_cast<_notmuch_features>(0);
680 unsigned int namelen, i;
684 /* Prior to database version 3, features were implied by the
687 return NOTMUCH_FEATURES_V0;
688 else if (version == 1)
689 return NOTMUCH_FEATURES_V1;
690 else if (version == 2)
691 return NOTMUCH_FEATURES_V2;
693 /* Parse the features string */
694 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
695 flags = strchr (features, '\t');
696 if (! flags || flags > features + llen)
698 namelen = flags - features;
700 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
701 if (strlen (feature_names[i].name) == namelen &&
702 strncmp (feature_names[i].name, features, namelen) == 0) {
703 res |= feature_names[i].value;
708 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
709 /* Unrecognized feature */
710 const char *have = strchr (flags, mode);
711 if (have && have < features + llen) {
712 /* This feature is required to access this database in
713 * 'mode', but we don't understand it. */
715 *incompat_out = talloc_strdup (ctx, "");
716 *incompat_out = talloc_asprintf_append_buffer (
717 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
727 _print_features (const void *ctx, unsigned int features)
730 char *res = talloc_strdup (ctx, "");
732 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
733 if (features & feature_names[i].value)
734 res = talloc_asprintf_append_buffer (
735 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
741 notmuch_database_open (const char *path,
742 notmuch_database_mode_t mode,
743 notmuch_database_t **database)
745 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
746 void *local = talloc_new (NULL);
747 notmuch_database_t *notmuch = NULL;
748 char *notmuch_path, *xapian_path, *incompat_features;
751 unsigned int i, version;
752 static int initialized = 0;
755 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
756 status = NOTMUCH_STATUS_NULL_POINTER;
760 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
761 fprintf (stderr, "Out of memory\n");
762 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
766 err = stat (notmuch_path, &st);
768 fprintf (stderr, "Error opening database at %s: %s\n",
769 notmuch_path, strerror (errno));
770 status = NOTMUCH_STATUS_FILE_ERROR;
774 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
775 fprintf (stderr, "Out of memory\n");
776 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
780 /* Initialize the GLib type system and threads */
781 #if !GLIB_CHECK_VERSION(2, 35, 1)
785 /* Initialize gmime */
787 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
791 notmuch = talloc_zero (NULL, notmuch_database_t);
792 notmuch->exception_reported = FALSE;
793 notmuch->path = talloc_strdup (notmuch, path);
795 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
796 notmuch->path[strlen (notmuch->path) - 1] = '\0';
798 notmuch->mode = mode;
799 notmuch->atomic_nesting = 0;
801 string last_thread_id;
803 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
804 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
805 Xapian::DB_CREATE_OR_OPEN);
807 notmuch->xapian_db = new Xapian::Database (xapian_path);
810 /* Check version. As of database version 3, we represent
811 * changes in terms of features, so assume a version bump
812 * means a dramatically incompatible change. */
813 version = notmuch_database_get_version (notmuch);
814 if (version > NOTMUCH_DATABASE_VERSION) {
816 "Error: Notmuch database at %s\n"
817 " has a newer database format version (%u) than supported by this\n"
818 " version of notmuch (%u).\n",
819 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
820 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
821 notmuch_database_destroy (notmuch);
823 status = NOTMUCH_STATUS_FILE_ERROR;
827 /* Check features. */
828 incompat_features = NULL;
829 notmuch->features = _parse_features (
830 local, notmuch->xapian_db->get_metadata ("features").c_str (),
831 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
833 if (incompat_features) {
835 "Error: Notmuch database at %s\n"
836 " requires features (%s)\n"
837 " not supported by this version of notmuch.\n",
838 notmuch_path, incompat_features);
839 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
840 notmuch_database_destroy (notmuch);
842 status = NOTMUCH_STATUS_FILE_ERROR;
846 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
847 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
848 if (last_thread_id.empty ()) {
849 notmuch->last_thread_id = 0;
854 str = last_thread_id.c_str ();
855 notmuch->last_thread_id = strtoull (str, &end, 16);
857 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
860 notmuch->query_parser = new Xapian::QueryParser;
861 notmuch->term_gen = new Xapian::TermGenerator;
862 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
863 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
864 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
866 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
867 notmuch->query_parser->set_database (*notmuch->xapian_db);
868 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
869 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
870 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
871 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
873 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
874 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
875 notmuch->query_parser->add_boolean_prefix (prefix->name,
879 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
880 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
881 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
883 } catch (const Xapian::Error &error) {
884 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
885 error.get_msg().c_str());
886 notmuch_database_destroy (notmuch);
888 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
897 talloc_free (notmuch);
902 notmuch_database_close (notmuch_database_t *notmuch)
904 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
907 if (notmuch->xapian_db != NULL &&
908 notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
909 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
910 } catch (const Xapian::Error &error) {
911 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
912 if (! notmuch->exception_reported) {
913 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
914 error.get_msg().c_str());
918 /* Many Xapian objects (and thus notmuch objects) hold references to
919 * the database, so merely deleting the database may not suffice to
920 * close it. Thus, we explicitly close it here. */
921 if (notmuch->xapian_db != NULL) {
923 notmuch->xapian_db->close();
924 } catch (const Xapian::Error &error) {
925 /* don't clobber previous error status */
926 if (status == NOTMUCH_STATUS_SUCCESS)
927 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
931 delete notmuch->term_gen;
932 notmuch->term_gen = NULL;
933 delete notmuch->query_parser;
934 notmuch->query_parser = NULL;
935 delete notmuch->xapian_db;
936 notmuch->xapian_db = NULL;
937 delete notmuch->value_range_processor;
938 notmuch->value_range_processor = NULL;
939 delete notmuch->date_range_processor;
940 notmuch->date_range_processor = NULL;
945 #if HAVE_XAPIAN_COMPACT
947 unlink_cb (const char *path,
948 unused (const struct stat *sb),
950 unused (struct FTW *ftw))
952 return remove (path);
956 rmtree (const char *path)
958 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
961 class NotmuchCompactor : public Xapian::Compactor
963 notmuch_compact_status_cb_t status_cb;
964 void *status_closure;
967 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
968 status_cb (cb), status_closure (closure) { }
971 set_status (const std::string &table, const std::string &status)
975 if (status_cb == NULL)
978 if (status.length () == 0)
979 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
981 msg = talloc_asprintf (NULL, " %s", status.c_str());
987 status_cb (msg, status_closure);
992 /* Compacts the given database, optionally saving the original database
993 * in backup_path. Additionally, a callback function can be provided to
994 * give the user feedback on the progress of the (likely long-lived)
995 * compaction process.
997 * The backup path must point to a directory on the same volume as the
998 * original database. Passing a NULL backup_path will result in the
999 * uncompacted database being deleted after compaction has finished.
1000 * Note that the database write lock will be held during the
1001 * compaction process to protect data integrity.
1004 notmuch_database_compact (const char *path,
1005 const char *backup_path,
1006 notmuch_compact_status_cb_t status_cb,
1010 char *notmuch_path, *xapian_path, *compact_xapian_path;
1011 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1012 notmuch_database_t *notmuch = NULL;
1013 struct stat statbuf;
1014 notmuch_bool_t keep_backup;
1016 local = talloc_new (NULL);
1018 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1020 ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
1025 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1026 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1030 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1031 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1035 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1036 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1040 if (backup_path == NULL) {
1041 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1042 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1045 keep_backup = FALSE;
1051 if (stat (backup_path, &statbuf) != -1) {
1052 fprintf (stderr, "Path already exists: %s\n", backup_path);
1053 ret = NOTMUCH_STATUS_FILE_ERROR;
1056 if (errno != ENOENT) {
1057 fprintf (stderr, "Unknown error while stat()ing path: %s\n",
1059 ret = NOTMUCH_STATUS_FILE_ERROR;
1063 /* Unconditionally attempt to remove old work-in-progress database (if
1064 * any). This is "protected" by database lock. If this fails due to write
1065 * errors (etc), the following code will fail and provide error message.
1067 (void) rmtree (compact_xapian_path);
1070 NotmuchCompactor compactor (status_cb, closure);
1072 compactor.set_renumber (false);
1073 compactor.add_source (xapian_path);
1074 compactor.set_destdir (compact_xapian_path);
1075 compactor.compact ();
1076 } catch (const Xapian::Error &error) {
1077 fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
1078 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1082 if (rename (xapian_path, backup_path)) {
1083 fprintf (stderr, "Error moving %s to %s: %s\n",
1084 xapian_path, backup_path, strerror (errno));
1085 ret = NOTMUCH_STATUS_FILE_ERROR;
1089 if (rename (compact_xapian_path, xapian_path)) {
1090 fprintf (stderr, "Error moving %s to %s: %s\n",
1091 compact_xapian_path, xapian_path, strerror (errno));
1092 ret = NOTMUCH_STATUS_FILE_ERROR;
1096 if (! keep_backup) {
1097 if (rmtree (backup_path)) {
1098 fprintf (stderr, "Error removing old database %s: %s\n",
1099 backup_path, strerror (errno));
1100 ret = NOTMUCH_STATUS_FILE_ERROR;
1107 notmuch_status_t ret2;
1109 ret2 = notmuch_database_destroy (notmuch);
1111 /* don't clobber previous error status */
1112 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1116 talloc_free (local);
1122 notmuch_database_compact (unused (const char *path),
1123 unused (const char *backup_path),
1124 unused (notmuch_compact_status_cb_t status_cb),
1125 unused (void *closure))
1127 fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
1128 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1133 notmuch_database_destroy (notmuch_database_t *notmuch)
1135 notmuch_status_t status;
1137 status = notmuch_database_close (notmuch);
1138 talloc_free (notmuch);
1144 notmuch_database_get_path (notmuch_database_t *notmuch)
1146 return notmuch->path;
1150 notmuch_database_get_version (notmuch_database_t *notmuch)
1152 unsigned int version;
1153 string version_string;
1157 version_string = notmuch->xapian_db->get_metadata ("version");
1158 if (version_string.empty ())
1161 str = version_string.c_str ();
1162 if (str == NULL || *str == '\0')
1165 version = strtoul (str, &end, 10);
1167 INTERNAL_ERROR ("Malformed database version: %s", str);
1173 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1175 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1176 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1177 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1180 static volatile sig_atomic_t do_progress_notify = 0;
1183 handle_sigalrm (unused (int signal))
1185 do_progress_notify = 1;
1188 /* Upgrade the current database.
1190 * After opening a database in read-write mode, the client should
1191 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1192 * if so, upgrade with this function before making any modifications.
1194 * The optional progress_notify callback can be used by the caller to
1195 * provide progress indication to the user. If non-NULL it will be
1196 * called periodically with 'count' as the number of messages upgraded
1197 * so far and 'total' the overall number of messages that will be
1201 notmuch_database_upgrade (notmuch_database_t *notmuch,
1202 void (*progress_notify) (void *closure,
1206 void *local = talloc_new (NULL);
1207 Xapian::TermIterator t, t_end;
1208 Xapian::WritableDatabase *db;
1209 struct sigaction action;
1210 struct itimerval timerval;
1211 notmuch_bool_t timer_is_active = FALSE;
1212 enum _notmuch_features target_features, new_features;
1213 notmuch_status_t status;
1214 unsigned int count = 0, total = 0;
1216 status = _notmuch_database_ensure_writable (notmuch);
1220 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1222 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1223 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1226 return NOTMUCH_STATUS_SUCCESS;
1228 if (progress_notify) {
1229 /* Setup our handler for SIGALRM */
1230 memset (&action, 0, sizeof (struct sigaction));
1231 action.sa_handler = handle_sigalrm;
1232 sigemptyset (&action.sa_mask);
1233 action.sa_flags = SA_RESTART;
1234 sigaction (SIGALRM, &action, NULL);
1236 /* Then start a timer to send SIGALRM once per second. */
1237 timerval.it_interval.tv_sec = 1;
1238 timerval.it_interval.tv_usec = 0;
1239 timerval.it_value.tv_sec = 1;
1240 timerval.it_value.tv_usec = 0;
1241 setitimer (ITIMER_REAL, &timerval, NULL);
1243 timer_is_active = TRUE;
1246 /* Figure out how much total work we need to do. */
1248 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1249 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1250 total += notmuch_query_count_messages (query);
1251 notmuch_query_destroy (query);
1253 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1254 t_end = db->allterms_end ("XTIMESTAMP");
1255 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1259 /* Perform the upgrade in a transaction. */
1260 db->begin_transaction (true);
1262 /* Set the target features so we write out changes in the desired
1264 notmuch->features = target_features;
1266 /* Perform per-message upgrades. */
1268 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1269 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1270 notmuch_messages_t *messages;
1271 notmuch_message_t *message;
1274 for (messages = notmuch_query_search_messages (query);
1275 notmuch_messages_valid (messages);
1276 notmuch_messages_move_to_next (messages))
1278 if (do_progress_notify) {
1279 progress_notify (closure, (double) count / total);
1280 do_progress_notify = 0;
1283 message = notmuch_messages_get (messages);
1285 /* Before version 1, each message document had its
1286 * filename in the data field. Copy that into the new
1287 * format by calling notmuch_message_add_filename.
1289 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1290 filename = _notmuch_message_talloc_copy_data (message);
1291 if (filename && *filename != '\0') {
1292 _notmuch_message_add_filename (message, filename);
1293 _notmuch_message_clear_data (message);
1295 talloc_free (filename);
1298 /* Prior to version 2, the "folder:" prefix was
1299 * probabilistic and stemmed. Change it to the current
1300 * boolean prefix. Add "path:" prefixes while at it.
1302 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1303 _notmuch_message_upgrade_folder (message);
1305 _notmuch_message_sync (message);
1307 notmuch_message_destroy (message);
1312 notmuch_query_destroy (query);
1315 /* Perform per-directory upgrades. */
1317 /* Before version 1 we stored directory timestamps in
1318 * XTIMESTAMP documents instead of the current XDIRECTORY
1319 * documents. So copy those as well. */
1320 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1321 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1323 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1327 Xapian::PostingIterator p, p_end;
1328 std::string term = *t;
1330 p_end = notmuch->xapian_db->postlist_end (term);
1332 for (p = notmuch->xapian_db->postlist_begin (term);
1336 Xapian::Document document;
1338 notmuch_directory_t *directory;
1340 if (do_progress_notify) {
1341 progress_notify (closure, (double) count / total);
1342 do_progress_notify = 0;
1345 document = find_document_for_doc_id (notmuch, *p);
1346 mtime = Xapian::sortable_unserialise (
1347 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1349 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1350 NOTMUCH_FIND_CREATE, &status);
1351 notmuch_directory_set_mtime (directory, mtime);
1352 notmuch_directory_destroy (directory);
1354 db->delete_document (*p);
1361 db->set_metadata ("features", _print_features (local, notmuch->features));
1362 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1364 db->commit_transaction ();
1366 if (timer_is_active) {
1367 /* Now stop the timer. */
1368 timerval.it_interval.tv_sec = 0;
1369 timerval.it_interval.tv_usec = 0;
1370 timerval.it_value.tv_sec = 0;
1371 timerval.it_value.tv_usec = 0;
1372 setitimer (ITIMER_REAL, &timerval, NULL);
1374 /* And disable the signal handler. */
1375 action.sa_handler = SIG_IGN;
1376 sigaction (SIGALRM, &action, NULL);
1379 talloc_free (local);
1380 return NOTMUCH_STATUS_SUCCESS;
1384 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1386 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1387 notmuch->atomic_nesting > 0)
1391 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1392 } catch (const Xapian::Error &error) {
1393 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1394 error.get_msg().c_str());
1395 notmuch->exception_reported = TRUE;
1396 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1400 notmuch->atomic_nesting++;
1401 return NOTMUCH_STATUS_SUCCESS;
1405 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1407 Xapian::WritableDatabase *db;
1409 if (notmuch->atomic_nesting == 0)
1410 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1412 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1413 notmuch->atomic_nesting > 1)
1416 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1418 db->commit_transaction ();
1420 /* This is a hack for testing. Xapian never flushes on a
1421 * non-flushed commit, even if the flush threshold is 1.
1422 * However, we rely on flushing to test atomicity. */
1423 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1424 if (thresh && atoi (thresh) == 1)
1426 } catch (const Xapian::Error &error) {
1427 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1428 error.get_msg().c_str());
1429 notmuch->exception_reported = TRUE;
1430 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1434 notmuch->atomic_nesting--;
1435 return NOTMUCH_STATUS_SUCCESS;
1438 /* We allow the user to use arbitrarily long paths for directories. But
1439 * we have a term-length limit. So if we exceed that, we'll use the
1440 * SHA-1 of the path for the database term.
1442 * Note: This function may return the original value of 'path'. If it
1443 * does not, then the caller is responsible to free() the returned
1447 _notmuch_database_get_directory_db_path (const char *path)
1449 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1451 if (term_len > NOTMUCH_TERM_MAX)
1452 return _notmuch_sha1_of_string (path);
1457 /* Given a path, split it into two parts: the directory part is all
1458 * components except for the last, and the basename is that last
1459 * component. Getting the return-value for either part is optional
1460 * (the caller can pass NULL).
1462 * The original 'path' can represent either a regular file or a
1463 * directory---the splitting will be carried out in the same way in
1464 * either case. Trailing slashes on 'path' will be ignored, and any
1465 * cases of multiple '/' characters appearing in series will be
1466 * treated as a single '/'.
1468 * Allocation (if any) will have 'ctx' as the talloc owner. But
1469 * pointers will be returned within the original path string whenever
1472 * Note: If 'path' is non-empty and contains no non-trailing slash,
1473 * (that is, consists of a filename with no parent directory), then
1474 * the directory returned will be an empty string. However, if 'path'
1475 * is an empty string, then both directory and basename will be
1479 _notmuch_database_split_path (void *ctx,
1481 const char **directory,
1482 const char **basename)
1486 if (path == NULL || *path == '\0') {
1491 return NOTMUCH_STATUS_SUCCESS;
1494 /* Find the last slash (not counting a trailing slash), if any. */
1496 slash = path + strlen (path) - 1;
1498 /* First, skip trailing slashes. */
1499 while (slash != path) {
1506 /* Then, find a slash. */
1507 while (slash != path) {
1517 /* Finally, skip multiple slashes. */
1518 while (slash != path) {
1525 if (slash == path) {
1527 *directory = talloc_strdup (ctx, "");
1532 *directory = talloc_strndup (ctx, path, slash - path + 1);
1535 return NOTMUCH_STATUS_SUCCESS;
1538 /* Find the document ID of the specified directory.
1540 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1541 * created if one does not exist for 'path'. Otherwise, if the
1542 * directory document does not exist, this sets *directory_id to
1543 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1546 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1548 notmuch_find_flags_t flags,
1549 unsigned int *directory_id)
1551 notmuch_directory_t *directory;
1552 notmuch_status_t status;
1556 return NOTMUCH_STATUS_SUCCESS;
1559 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1560 if (status || !directory) {
1565 *directory_id = _notmuch_directory_get_document_id (directory);
1567 notmuch_directory_destroy (directory);
1569 return NOTMUCH_STATUS_SUCCESS;
1573 _notmuch_database_get_directory_path (void *ctx,
1574 notmuch_database_t *notmuch,
1575 unsigned int doc_id)
1577 Xapian::Document document;
1579 document = find_document_for_doc_id (notmuch, doc_id);
1581 return talloc_strdup (ctx, document.get_data ().c_str ());
1584 /* Given a legal 'filename' for the database, (either relative to
1585 * database path or absolute with initial components identical to
1586 * database path), return a new string (with 'ctx' as the talloc
1587 * owner) suitable for use as a direntry term value.
1589 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1590 * will be created in the database as needed. Otherwise, if the
1591 * necessary directory documents do not exist, this sets
1592 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1595 _notmuch_database_filename_to_direntry (void *ctx,
1596 notmuch_database_t *notmuch,
1597 const char *filename,
1598 notmuch_find_flags_t flags,
1601 const char *relative, *directory, *basename;
1602 Xapian::docid directory_id;
1603 notmuch_status_t status;
1605 relative = _notmuch_database_relative_path (notmuch, filename);
1607 status = _notmuch_database_split_path (ctx, relative,
1608 &directory, &basename);
1612 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1614 if (status || directory_id == (unsigned int)-1) {
1619 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1621 return NOTMUCH_STATUS_SUCCESS;
1624 /* Given a legal 'path' for the database, return the relative path.
1626 * The return value will be a pointer to the original path contents,
1627 * and will be either the original string (if 'path' was relative) or
1628 * a portion of the string (if path was absolute and begins with the
1632 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1635 const char *db_path, *relative;
1636 unsigned int db_path_len;
1638 db_path = notmuch_database_get_path (notmuch);
1639 db_path_len = strlen (db_path);
1643 if (*relative == '/') {
1644 while (*relative == '/' && *(relative+1) == '/')
1647 if (strncmp (relative, db_path, db_path_len) == 0)
1649 relative += db_path_len;
1650 while (*relative == '/')
1659 notmuch_database_get_directory (notmuch_database_t *notmuch,
1661 notmuch_directory_t **directory)
1663 notmuch_status_t status;
1665 if (directory == NULL)
1666 return NOTMUCH_STATUS_NULL_POINTER;
1670 *directory = _notmuch_directory_create (notmuch, path,
1671 NOTMUCH_FIND_LOOKUP, &status);
1672 } catch (const Xapian::Error &error) {
1673 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1674 error.get_msg().c_str());
1675 notmuch->exception_reported = TRUE;
1676 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1681 /* Allocate a document ID that satisfies the following criteria:
1683 * 1. The ID does not exist for any document in the Xapian database
1685 * 2. The ID was not previously returned from this function
1687 * 3. The ID is the smallest integer satisfying (1) and (2)
1689 * This function will trigger an internal error if these constraints
1690 * cannot all be satisfied, (that is, the pool of available document
1691 * IDs has been exhausted).
1694 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1696 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1698 notmuch->last_doc_id++;
1700 if (notmuch->last_doc_id == 0)
1701 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1703 return notmuch->last_doc_id;
1707 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1709 /* 16 bytes (+ terminator) for hexadecimal representation of
1710 * a 64-bit integer. */
1711 static char thread_id[17];
1712 Xapian::WritableDatabase *db;
1714 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1716 notmuch->last_thread_id++;
1718 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1720 db->set_metadata ("last_thread_id", thread_id);
1726 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1728 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1729 message_id = _message_id_compressed (ctx, message_id);
1731 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1735 /* Find the thread ID to which the message with 'message_id' belongs.
1737 * Note: 'thread_id_ret' must not be NULL!
1738 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1741 * Note: If there is no message in the database with the given
1742 * 'message_id' then a new thread_id will be allocated for this
1743 * message and stored in the database metadata, (where this same
1744 * thread ID can be looked up if the message is added to the database
1747 static notmuch_status_t
1748 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1750 const char *message_id,
1751 const char **thread_id_ret)
1753 notmuch_status_t status;
1754 notmuch_message_t *message;
1755 string thread_id_string;
1757 Xapian::WritableDatabase *db;
1759 status = notmuch_database_find_message (notmuch, message_id, &message);
1765 *thread_id_ret = talloc_steal (ctx,
1766 notmuch_message_get_thread_id (message));
1768 notmuch_message_destroy (message);
1770 return NOTMUCH_STATUS_SUCCESS;
1773 /* Message has not been seen yet.
1775 * We may have seen a reference to it already, in which case, we
1776 * can return the thread ID stored in the metadata. Otherwise, we
1777 * generate a new thread ID and store it there.
1779 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1780 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1781 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1783 if (thread_id_string.empty()) {
1784 *thread_id_ret = talloc_strdup (ctx,
1785 _notmuch_database_generate_thread_id (notmuch));
1786 db->set_metadata (metadata_key, *thread_id_ret);
1788 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1791 talloc_free (metadata_key);
1793 return NOTMUCH_STATUS_SUCCESS;
1796 static notmuch_status_t
1797 _merge_threads (notmuch_database_t *notmuch,
1798 const char *winner_thread_id,
1799 const char *loser_thread_id)
1801 Xapian::PostingIterator loser, loser_end;
1802 notmuch_message_t *message = NULL;
1803 notmuch_private_status_t private_status;
1804 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1806 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1808 for ( ; loser != loser_end; loser++) {
1809 message = _notmuch_message_create (notmuch, notmuch,
1810 *loser, &private_status);
1811 if (message == NULL) {
1812 ret = COERCE_STATUS (private_status,
1813 "Cannot find document for doc_id from query");
1817 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1818 _notmuch_message_add_term (message, "thread", winner_thread_id);
1819 _notmuch_message_sync (message);
1821 notmuch_message_destroy (message);
1827 notmuch_message_destroy (message);
1833 _my_talloc_free_for_g_hash (void *ptr)
1838 static notmuch_status_t
1839 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1840 notmuch_message_t *message,
1841 notmuch_message_file_t *message_file,
1842 const char **thread_id)
1844 GHashTable *parents = NULL;
1845 const char *refs, *in_reply_to, *in_reply_to_message_id;
1846 const char *last_ref_message_id, *this_message_id;
1847 GList *l, *keys = NULL;
1848 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1850 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1851 _my_talloc_free_for_g_hash, NULL);
1852 this_message_id = notmuch_message_get_message_id (message);
1854 refs = _notmuch_message_file_get_header (message_file, "references");
1855 last_ref_message_id = parse_references (message,
1859 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
1860 in_reply_to_message_id = parse_references (message,
1862 parents, in_reply_to);
1864 /* For the parent of this message, use the last message ID of the
1865 * References header, if available. If not, fall back to the
1866 * first message ID in the In-Reply-To header. */
1867 if (last_ref_message_id) {
1868 _notmuch_message_add_term (message, "replyto",
1869 last_ref_message_id);
1870 } else if (in_reply_to_message_id) {
1871 _notmuch_message_add_term (message, "replyto",
1872 in_reply_to_message_id);
1875 keys = g_hash_table_get_keys (parents);
1876 for (l = keys; l; l = l->next) {
1877 char *parent_message_id;
1878 const char *parent_thread_id = NULL;
1880 parent_message_id = (char *) l->data;
1882 _notmuch_message_add_term (message, "reference",
1885 ret = _resolve_message_id_to_thread_id (notmuch,
1892 if (*thread_id == NULL) {
1893 *thread_id = talloc_strdup (message, parent_thread_id);
1894 _notmuch_message_add_term (message, "thread", *thread_id);
1895 } else if (strcmp (*thread_id, parent_thread_id)) {
1896 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1906 g_hash_table_unref (parents);
1911 static notmuch_status_t
1912 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1913 notmuch_message_t *message,
1914 const char **thread_id)
1916 const char *message_id = notmuch_message_get_message_id (message);
1917 Xapian::PostingIterator child, children_end;
1918 notmuch_message_t *child_message = NULL;
1919 const char *child_thread_id;
1920 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1921 notmuch_private_status_t private_status;
1923 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1925 for ( ; child != children_end; child++) {
1927 child_message = _notmuch_message_create (message, notmuch,
1928 *child, &private_status);
1929 if (child_message == NULL) {
1930 ret = COERCE_STATUS (private_status,
1931 "Cannot find document for doc_id from query");
1935 child_thread_id = notmuch_message_get_thread_id (child_message);
1936 if (*thread_id == NULL) {
1937 *thread_id = talloc_strdup (message, child_thread_id);
1938 _notmuch_message_add_term (message, "thread", *thread_id);
1939 } else if (strcmp (*thread_id, child_thread_id)) {
1940 _notmuch_message_remove_term (child_message, "reference",
1942 _notmuch_message_sync (child_message);
1943 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1948 notmuch_message_destroy (child_message);
1949 child_message = NULL;
1954 notmuch_message_destroy (child_message);
1959 /* Given a (mostly empty) 'message' and its corresponding
1960 * 'message_file' link it to existing threads in the database.
1962 * The first check is in the metadata of the database to see if we
1963 * have pre-allocated a thread_id in advance for this message, (which
1964 * would have happened if a message was previously added that
1965 * referenced this one).
1967 * Second, we look at 'message_file' and its link-relevant headers
1968 * (References and In-Reply-To) for message IDs.
1970 * Finally, we look in the database for existing message that
1971 * reference 'message'.
1973 * In all cases, we assign to the current message the first thread_id
1974 * found (through either parent or child). We will also merge any
1975 * existing, distinct threads where this message belongs to both,
1976 * (which is not uncommon when messages are processed out of order).
1978 * Finally, if no thread ID has been found through parent or child, we
1979 * call _notmuch_message_generate_thread_id to generate a new thread
1980 * ID. This should only happen for new, top-level messages, (no
1981 * References or In-Reply-To header in this message, and no previously
1982 * added message refers to this message).
1984 static notmuch_status_t
1985 _notmuch_database_link_message (notmuch_database_t *notmuch,
1986 notmuch_message_t *message,
1987 notmuch_message_file_t *message_file)
1989 notmuch_status_t status;
1990 const char *message_id, *thread_id = NULL;
1994 message_id = notmuch_message_get_message_id (message);
1995 metadata_key = _get_metadata_thread_id_key (message, message_id);
1997 /* Check if we have already seen related messages to this one.
1998 * If we have then use the thread_id that we stored at that time.
2000 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2001 if (! stored_id.empty()) {
2002 Xapian::WritableDatabase *db;
2004 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2006 /* Clear the metadata for this message ID. We don't need it
2008 db->set_metadata (metadata_key, "");
2009 thread_id = stored_id.c_str();
2011 _notmuch_message_add_term (message, "thread", thread_id);
2013 talloc_free (metadata_key);
2015 status = _notmuch_database_link_message_to_parents (notmuch, message,
2021 status = _notmuch_database_link_message_to_children (notmuch, message,
2026 /* If not part of any existing thread, generate a new thread ID. */
2027 if (thread_id == NULL) {
2028 thread_id = _notmuch_database_generate_thread_id (notmuch);
2030 _notmuch_message_add_term (message, "thread", thread_id);
2033 return NOTMUCH_STATUS_SUCCESS;
2037 notmuch_database_add_message (notmuch_database_t *notmuch,
2038 const char *filename,
2039 notmuch_message_t **message_ret)
2041 notmuch_message_file_t *message_file;
2042 notmuch_message_t *message = NULL;
2043 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2044 notmuch_private_status_t private_status;
2046 const char *date, *header;
2047 const char *from, *to, *subject;
2048 char *message_id = NULL;
2051 *message_ret = NULL;
2053 ret = _notmuch_database_ensure_writable (notmuch);
2057 message_file = _notmuch_message_file_open (filename);
2058 if (message_file == NULL)
2059 return NOTMUCH_STATUS_FILE_ERROR;
2061 /* Adding a message may change many documents. Do this all
2063 ret = notmuch_database_begin_atomic (notmuch);
2067 /* Parse message up front to get better error status. */
2068 ret = _notmuch_message_file_parse (message_file);
2073 /* Before we do any real work, (especially before doing a
2074 * potential SHA-1 computation on the entire file's contents),
2075 * let's make sure that what we're looking at looks like an
2076 * actual email message.
2078 from = _notmuch_message_file_get_header (message_file, "from");
2079 subject = _notmuch_message_file_get_header (message_file, "subject");
2080 to = _notmuch_message_file_get_header (message_file, "to");
2082 if ((from == NULL || *from == '\0') &&
2083 (subject == NULL || *subject == '\0') &&
2084 (to == NULL || *to == '\0'))
2086 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2090 /* Now that we're sure it's mail, the first order of business
2091 * is to find a message ID (or else create one ourselves). */
2093 header = _notmuch_message_file_get_header (message_file, "message-id");
2094 if (header && *header != '\0') {
2095 message_id = _parse_message_id (message_file, header, NULL);
2097 /* So the header value isn't RFC-compliant, but it's
2098 * better than no message-id at all. */
2099 if (message_id == NULL)
2100 message_id = talloc_strdup (message_file, header);
2102 /* If a message ID is too long, substitute its sha1 instead. */
2103 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
2104 char *compressed = _message_id_compressed (message_file,
2106 talloc_free (message_id);
2107 message_id = compressed;
2111 if (message_id == NULL ) {
2112 /* No message-id at all, let's generate one by taking a
2113 * hash over the file's contents. */
2114 char *sha1 = _notmuch_sha1_of_file (filename);
2116 /* If that failed too, something is really wrong. Give up. */
2118 ret = NOTMUCH_STATUS_FILE_ERROR;
2122 message_id = talloc_asprintf (message_file,
2123 "notmuch-sha1-%s", sha1);
2127 /* Now that we have a message ID, we get a message object,
2128 * (which may or may not reference an existing document in the
2131 message = _notmuch_message_create_for_message_id (notmuch,
2135 talloc_free (message_id);
2137 if (message == NULL) {
2138 ret = COERCE_STATUS (private_status,
2139 "Unexpected status value from _notmuch_message_create_for_message_id");
2143 _notmuch_message_add_filename (message, filename);
2145 /* Is this a newly created message object? */
2146 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2147 _notmuch_message_add_term (message, "type", "mail");
2149 ret = _notmuch_database_link_message (notmuch, message,
2154 date = _notmuch_message_file_get_header (message_file, "date");
2155 _notmuch_message_set_header_values (message, date, from, subject);
2157 ret = _notmuch_message_index_file (message, message_file);
2161 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2164 _notmuch_message_sync (message);
2165 } catch (const Xapian::Error &error) {
2166 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2167 error.get_msg().c_str());
2168 notmuch->exception_reported = TRUE;
2169 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2175 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2176 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2177 *message_ret = message;
2179 notmuch_message_destroy (message);
2183 _notmuch_message_file_close (message_file);
2185 ret2 = notmuch_database_end_atomic (notmuch);
2186 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2187 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2188 ret2 != NOTMUCH_STATUS_SUCCESS)
2195 notmuch_database_remove_message (notmuch_database_t *notmuch,
2196 const char *filename)
2198 notmuch_status_t status;
2199 notmuch_message_t *message;
2201 status = notmuch_database_find_message_by_filename (notmuch, filename,
2204 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2205 status = _notmuch_message_remove_filename (message, filename);
2206 if (status == NOTMUCH_STATUS_SUCCESS)
2207 _notmuch_message_delete (message);
2208 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2209 _notmuch_message_sync (message);
2211 notmuch_message_destroy (message);
2218 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2219 const char *filename,
2220 notmuch_message_t **message_ret)
2223 const char *prefix = _find_prefix ("file-direntry");
2224 char *direntry, *term;
2225 Xapian::PostingIterator i, end;
2226 notmuch_status_t status;
2228 if (message_ret == NULL)
2229 return NOTMUCH_STATUS_NULL_POINTER;
2231 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2232 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2234 /* return NULL on any failure */
2235 *message_ret = NULL;
2237 local = talloc_new (notmuch);
2240 status = _notmuch_database_filename_to_direntry (
2241 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2242 if (status || !direntry)
2245 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2247 find_doc_ids_for_term (notmuch, term, &i, &end);
2250 notmuch_private_status_t private_status;
2252 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2254 if (*message_ret == NULL)
2255 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2257 } catch (const Xapian::Error &error) {
2258 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2259 error.get_msg().c_str());
2260 notmuch->exception_reported = TRUE;
2261 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2265 talloc_free (local);
2267 if (status && *message_ret) {
2268 notmuch_message_destroy (*message_ret);
2269 *message_ret = NULL;
2274 notmuch_string_list_t *
2275 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2276 Xapian::TermIterator &end,
2279 int prefix_len = strlen (prefix);
2280 notmuch_string_list_t *list;
2282 list = _notmuch_string_list_create (ctx);
2283 if (unlikely (list == NULL))
2286 for (i.skip_to (prefix); i != end; i++) {
2287 /* Terminate loop at first term without desired prefix. */
2288 if (strncmp ((*i).c_str (), prefix, prefix_len))
2291 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2298 notmuch_database_get_all_tags (notmuch_database_t *db)
2300 Xapian::TermIterator i, end;
2301 notmuch_string_list_t *tags;
2304 i = db->xapian_db->allterms_begin();
2305 end = db->xapian_db->allterms_end();
2306 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2307 _find_prefix ("tag"));
2308 _notmuch_string_list_sort (tags);
2309 return _notmuch_tags_create (db, tags);
2310 } catch (const Xapian::Error &error) {
2311 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2312 error.get_msg().c_str());
2313 db->exception_reported = TRUE;