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"
24 #include "string-util.h"
33 #include <glib.h> /* g_free, GPtrArray, GHashTable */
34 #include <glib-object.h> /* g_type_init */
36 #include <gmime/gmime.h> /* g_mime_init */
40 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
47 #define NOTMUCH_DATABASE_VERSION 3
49 #define STRINGIFY(s) _SUB_STRINGIFY(s)
50 #define _SUB_STRINGIFY(s) #s
52 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
54 * We currently have three different types of documents (mail, ghost,
55 * and directory) and also some metadata.
59 * A mail document is associated with a particular email message. It
60 * is stored in one or more files on disk (though only one has its
61 * content indexed) and is uniquely identified by its "id" field
62 * (which is generally the message ID). It is indexed with the
63 * following prefixed terms which the database uses to construct
66 * Single terms of given prefix:
70 * id: Unique ID of mail. This is from the Message-ID header
71 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
72 * If it's present and too long, then we use
73 * "notmuch-sha1-<sha1_sum_of_message_id>".
74 * If this header is not present, we use
75 * "notmuch-sha1-<sha1_sum_of_entire_file>".
77 * thread: The ID of the thread to which the mail belongs
79 * replyto: The ID from the In-Reply-To header of the mail (if any).
81 * Multiple terms of given prefix:
83 * reference: All message IDs from In-Reply-To and References
84 * headers in the message.
86 * tag: Any tags associated with this message by the user.
88 * file-direntry: A colon-separated pair of values
89 * (INTEGER:STRING), where INTEGER is the
90 * document ID of a directory document, and
91 * STRING is the name of a file within that
92 * directory for this mail message.
94 * A mail document also has four values:
96 * TIMESTAMP: The time_t value corresponding to the message's
99 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
101 * FROM: The value of the "From" header
103 * SUBJECT: The value of the "Subject" header
105 * LAST_MOD: The revision number as of the last tag or
108 * In addition, terms from the content of the message are added with
109 * "from", "to", "attachment", and "subject" prefixes for use by the
110 * user in searching. Similarly, terms from the path of the mail
111 * message are added with "folder" and "path" prefixes. But the
112 * database doesn't really care itself about any of these.
114 * The data portion of a mail document is empty.
116 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
117 * -----------------------------------------------
118 * A ghost mail document is like a mail document, but where we don't
119 * have the message content. These are used to track thread reference
120 * information for messages we haven't received.
122 * A ghost mail document has type: ghost; id and thread fields that
123 * are identical to the mail document fields; and a MESSAGE_ID value.
127 * A directory document is used by a client of the notmuch library to
128 * maintain data necessary to allow for efficient polling of mail
131 * All directory documents contain one term:
133 * directory: The directory path (relative to the database path)
134 * Or the SHA1 sum of the directory path (if the
135 * path itself is too long to fit in a Xapian
138 * And all directory documents for directories other than top-level
139 * directories also contain the following term:
141 * directory-direntry: A colon-separated pair of values
142 * (INTEGER:STRING), where INTEGER is the
143 * document ID of the parent directory
144 * document, and STRING is the name of this
145 * directory within that parent.
147 * All directory documents have a single value:
149 * TIMESTAMP: The mtime of the directory (at last scan)
151 * The data portion of a directory document contains the path of the
152 * directory (relative to the database path).
156 * Xapian allows us to store arbitrary name-value pairs as
157 * "metadata". We currently use the following metadata names with the
160 * version The database schema version, (which is distinct
161 * from both the notmuch package version (see
162 * notmuch --version) and the libnotmuch library
163 * version. The version is stored as an base-10
164 * ASCII integer. The initial database version
165 * was 1, (though a schema existed before that
166 * were no "version" database value existed at
167 * all). Successive versions are allocated as
168 * changes are made to the database (such as by
169 * indexing new fields).
171 * features The set of features supported by this
172 * database. This consists of a set of
173 * '\n'-separated lines, where each is a feature
174 * name, a '\t', and compatibility flags. If the
175 * compatibility flags contain 'w', then the
176 * opener must support this feature to safely
177 * write this database. If the compatibility
178 * flags contain 'r', then the opener must
179 * support this feature to read this database.
180 * Introduced in database version 3.
182 * last_thread_id The last thread ID generated. This is stored
183 * as a 16-byte hexadecimal ASCII representation
184 * of a 64-bit unsigned integer. The first ID
185 * generated is 1 and the value will be
186 * incremented for each thread ID.
191 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
192 * Instead, the database has the following additional database
195 * thread_id_* A pre-allocated thread ID for a particular
196 * message. This is actually an arbitrarily large
197 * family of metadata name. Any particular name is
198 * formed by concatenating "thread_id_" with a message
199 * ID (or the SHA1 sum of a message ID if it is very
200 * long---see description of 'id' in the mail
201 * document). The value stored is a thread ID.
203 * These thread ID metadata values are stored
204 * whenever a message references a parent message
205 * that does not yet exist in the database. A
206 * thread ID will be allocated and stored, and if
207 * the message is later added, the stored thread
208 * ID will be used (and the metadata value will
211 * Even before a message is added, it's
212 * pre-allocated thread ID is useful so that all
213 * descendant messages that reference this common
214 * parent can be recognized as belonging to the
218 /* With these prefix values we follow the conventions published here:
220 * http://xapian.org/docs/omega/termprefixes.html
222 * as much as makes sense. Note that I took some liberty in matching
223 * the reserved prefix values to notmuch concepts, (for example, 'G'
224 * is documented as "newsGroup (or similar entity - e.g. a web forum
225 * name)", for which I think the thread is the closest analogue in
226 * notmuch. This in spite of the fact that we will eventually be
227 * storing mailing-list messages where 'G' for "mailing list name"
228 * might be even a closer analogue. I'm treating the single-character
229 * prefixes preferentially for core notmuch concepts (which will be
230 * nearly universal to all mail messages).
233 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
235 { "reference", "XREFERENCE" },
236 { "replyto", "XREPLYTO" },
237 { "directory", "XDIRECTORY" },
238 { "file-direntry", "XFDIRENTRY" },
239 { "directory-direntry", "XDDIRENTRY" },
242 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
249 * Without the ":", since this is a multi-letter prefix, Xapian
250 * will add a colon itself if the first letter of the path is
251 * upper-case ASCII. Including the ":" forces there to always be a
252 * colon, which keeps our own logic simpler.
254 { "folder", "XFOLDER:" },
257 static prefix_t PROBABILISTIC_PREFIX[]= {
260 { "attachment", "XATTACHMENT" },
261 { "mimetype", "XMIMETYPE"},
262 { "subject", "XSUBJECT"},
266 _find_prefix (const char *name)
270 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
271 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
272 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
275 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
276 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
277 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
280 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
281 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
282 return PROBABILISTIC_PREFIX[i].prefix;
285 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
290 static const struct {
291 /* NOTMUCH_FEATURE_* value. */
292 _notmuch_features value;
293 /* Feature name as it appears in the database. This name should
294 * be appropriate for displaying to the user if an older version
295 * of notmuch doesn't support this feature. */
297 /* Compatibility flags when this feature is declared. */
299 } feature_names[] = {
300 { NOTMUCH_FEATURE_FILE_TERMS,
301 "multiple paths per message", "rw" },
302 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
303 "relative directory paths", "rw" },
304 /* Header values are not required for reading a database because a
305 * reader can just refer to the message file. */
306 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
307 "from/subject/message-ID in database", "w" },
308 { NOTMUCH_FEATURE_BOOL_FOLDER,
309 "exact folder:/path: search", "rw" },
310 { NOTMUCH_FEATURE_GHOSTS,
311 "mail documents for missing messages", "w"},
312 /* Knowledge of the index mime-types are not required for reading
313 * a database because a reader will just be unable to query
315 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
316 "indexed MIME types", "w"},
317 { NOTMUCH_FEATURE_LAST_MOD,
318 "modification tracking", "w"},
322 notmuch_status_to_string (notmuch_status_t status)
325 case NOTMUCH_STATUS_SUCCESS:
326 return "No error occurred";
327 case NOTMUCH_STATUS_OUT_OF_MEMORY:
328 return "Out of memory";
329 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
330 return "Attempt to write to a read-only database";
331 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
332 return "A Xapian exception occurred";
333 case NOTMUCH_STATUS_FILE_ERROR:
334 return "Something went wrong trying to read or write a file";
335 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
336 return "File is not an email";
337 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
338 return "Message ID is identical to a message in database";
339 case NOTMUCH_STATUS_NULL_POINTER:
340 return "Erroneous NULL pointer";
341 case NOTMUCH_STATUS_TAG_TOO_LONG:
342 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
343 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
344 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
345 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
346 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
347 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
348 return "Unsupported operation";
349 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
350 return "Operation requires a database upgrade";
351 case NOTMUCH_STATUS_PATH_ERROR:
352 return "Path supplied is illegal for this function";
354 case NOTMUCH_STATUS_LAST_STATUS:
355 return "Unknown error status value";
360 _notmuch_database_log (notmuch_database_t *notmuch,
366 va_start (va_args, format);
368 if (notmuch->status_string)
369 talloc_free (notmuch->status_string);
371 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
377 find_doc_ids_for_term (notmuch_database_t *notmuch,
379 Xapian::PostingIterator *begin,
380 Xapian::PostingIterator *end)
382 *begin = notmuch->xapian_db->postlist_begin (term);
384 *end = notmuch->xapian_db->postlist_end (term);
388 find_doc_ids (notmuch_database_t *notmuch,
389 const char *prefix_name,
391 Xapian::PostingIterator *begin,
392 Xapian::PostingIterator *end)
396 term = talloc_asprintf (notmuch, "%s%s",
397 _find_prefix (prefix_name), value);
399 find_doc_ids_for_term (notmuch, term, begin, end);
404 notmuch_private_status_t
405 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
406 const char *prefix_name,
408 unsigned int *doc_id)
410 Xapian::PostingIterator i, end;
412 find_doc_ids (notmuch, prefix_name, value, &i, &end);
416 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
421 #if DEBUG_DATABASE_SANITY
425 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
429 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
432 static Xapian::Document
433 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
435 return notmuch->xapian_db->get_document (doc_id);
438 /* Generate a compressed version of 'message_id' of the form:
440 * notmuch-sha1-<sha1_sum_of_message_id>
443 _notmuch_message_id_compressed (void *ctx, const char *message_id)
445 char *sha1, *compressed;
447 sha1 = _notmuch_sha1_of_string (message_id);
449 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
456 notmuch_database_find_message (notmuch_database_t *notmuch,
457 const char *message_id,
458 notmuch_message_t **message_ret)
460 notmuch_private_status_t status;
463 if (message_ret == NULL)
464 return NOTMUCH_STATUS_NULL_POINTER;
466 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
467 message_id = _notmuch_message_id_compressed (notmuch, message_id);
470 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
471 message_id, &doc_id);
473 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
476 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
478 if (*message_ret == NULL)
479 return NOTMUCH_STATUS_OUT_OF_MEMORY;
482 return NOTMUCH_STATUS_SUCCESS;
483 } catch (const Xapian::Error &error) {
484 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
485 error.get_msg().c_str());
486 notmuch->exception_reported = TRUE;
488 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
492 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
493 * a (potentially nested) parenthesized sequence with '\' used to
494 * escape any character (including parentheses).
496 * If the sequence to be skipped continues to the end of the string,
497 * then 'str' will be left pointing at the final terminating '\0'
501 skip_space_and_comments (const char **str)
506 while (*s && (isspace (*s) || *s == '(')) {
507 while (*s && isspace (*s))
512 while (*s && nesting) {
515 } else if (*s == ')') {
517 } else if (*s == '\\') {
529 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
530 * comments, and the '<' and '>' delimiters.
532 * If not NULL, then *next will be made to point to the first character
533 * not parsed, (possibly pointing to the final '\0' terminator.
535 * Returns a newly talloc'ed string belonging to 'ctx'.
537 * Returns NULL if there is any error parsing the message-id. */
539 _parse_message_id (void *ctx, const char *message_id, const char **next)
544 if (message_id == NULL || *message_id == '\0')
549 skip_space_and_comments (&s);
551 /* Skip any unstructured text as well. */
552 while (*s && *s != '<')
563 skip_space_and_comments (&s);
566 while (*end && *end != '>')
575 if (end > s && *end == '>')
580 result = talloc_strndup (ctx, s, end - s + 1);
582 /* Finally, collapse any whitespace that is within the message-id
588 for (r = result, len = strlen (r); *r; r++, len--)
589 if (*r == ' ' || *r == '\t')
590 memmove (r, r+1, len);
596 /* Parse a References header value, putting a (talloc'ed under 'ctx')
597 * copy of each referenced message-id into 'hash'.
599 * We explicitly avoid including any reference identical to
600 * 'message_id' in the result (to avoid mass confusion when a single
601 * message references itself cyclically---and yes, mail messages are
602 * not infrequent in the wild that do this---don't ask me why).
604 * Return the last reference parsed, if it is not equal to message_id.
607 parse_references (void *ctx,
608 const char *message_id,
612 char *ref, *last_ref = NULL;
614 if (refs == NULL || *refs == '\0')
618 ref = _parse_message_id (ctx, refs, &refs);
620 if (ref && strcmp (ref, message_id)) {
621 g_hash_table_insert (hash, ref, NULL);
626 /* The return value of this function is used to add a parent
627 * reference to the database. We should avoid making a message
628 * its own parent, thus the above check.
634 notmuch_database_create (const char *path, notmuch_database_t **database)
636 char *status_string = NULL;
637 notmuch_status_t status;
639 status = notmuch_database_create_verbose (path, database,
643 fputs (status_string, stderr);
644 free (status_string);
651 notmuch_database_create_verbose (const char *path,
652 notmuch_database_t **database,
653 char **status_string)
655 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
656 notmuch_database_t *notmuch = NULL;
657 char *notmuch_path = NULL;
658 char *message = NULL;
663 message = strdup ("Error: Cannot create a database for a NULL path.\n");
664 status = NOTMUCH_STATUS_NULL_POINTER;
668 if (path[0] != '/') {
669 message = strdup ("Error: Database path must be absolute.\n");
670 status = NOTMUCH_STATUS_PATH_ERROR;
674 err = stat (path, &st);
676 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
677 path, strerror (errno)));
678 status = NOTMUCH_STATUS_FILE_ERROR;
682 if (! S_ISDIR (st.st_mode)) {
683 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
684 "Not a directory.\n",
686 status = NOTMUCH_STATUS_FILE_ERROR;
690 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
692 err = mkdir (notmuch_path, 0755);
695 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
696 notmuch_path, strerror (errno)));
697 status = NOTMUCH_STATUS_FILE_ERROR;
701 status = notmuch_database_open_verbose (path,
702 NOTMUCH_DATABASE_MODE_READ_WRITE,
707 /* Upgrade doesn't add these feature to existing databases, but
708 * new databases have them. */
709 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
710 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
712 status = notmuch_database_upgrade (notmuch, NULL, NULL);
714 notmuch_database_close(notmuch);
720 talloc_free (notmuch_path);
724 *status_string = message;
731 talloc_free (notmuch);
736 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
738 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
739 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
740 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
743 return NOTMUCH_STATUS_SUCCESS;
746 /* Allocate a revision number for the next change. */
748 _notmuch_database_new_revision (notmuch_database_t *notmuch)
750 unsigned long new_revision = notmuch->revision + 1;
752 /* If we're in an atomic section, hold off on updating the
753 * committed revision number until we commit the atomic section.
755 if (notmuch->atomic_nesting)
756 notmuch->atomic_dirty = TRUE;
758 notmuch->revision = new_revision;
763 /* Parse a database features string from the given database version.
764 * Returns the feature bit set.
766 * For version < 3, this ignores the features string and returns a
767 * hard-coded set of features.
769 * If there are unrecognized features that are required to open the
770 * database in mode (which should be 'r' or 'w'), return a
771 * comma-separated list of unrecognized but required features in
772 * *incompat_out suitable for presenting to the user. *incompat_out
773 * will be allocated from ctx.
775 static _notmuch_features
776 _parse_features (const void *ctx, const char *features, unsigned int version,
777 char mode, char **incompat_out)
779 _notmuch_features res = static_cast<_notmuch_features>(0);
780 unsigned int namelen, i;
784 /* Prior to database version 3, features were implied by the
787 return NOTMUCH_FEATURES_V0;
788 else if (version == 1)
789 return NOTMUCH_FEATURES_V1;
790 else if (version == 2)
791 return NOTMUCH_FEATURES_V2;
793 /* Parse the features string */
794 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
795 flags = strchr (features, '\t');
796 if (! flags || flags > features + llen)
798 namelen = flags - features;
800 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
801 if (strlen (feature_names[i].name) == namelen &&
802 strncmp (feature_names[i].name, features, namelen) == 0) {
803 res |= feature_names[i].value;
808 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
809 /* Unrecognized feature */
810 const char *have = strchr (flags, mode);
811 if (have && have < features + llen) {
812 /* This feature is required to access this database in
813 * 'mode', but we don't understand it. */
815 *incompat_out = talloc_strdup (ctx, "");
816 *incompat_out = talloc_asprintf_append_buffer (
817 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
827 _print_features (const void *ctx, unsigned int features)
830 char *res = talloc_strdup (ctx, "");
832 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
833 if (features & feature_names[i].value)
834 res = talloc_asprintf_append_buffer (
835 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
841 notmuch_database_open (const char *path,
842 notmuch_database_mode_t mode,
843 notmuch_database_t **database)
845 char *status_string = NULL;
846 notmuch_status_t status;
848 status = notmuch_database_open_verbose (path, mode, database,
852 fputs (status_string, stderr);
853 free (status_string);
860 notmuch_database_open_verbose (const char *path,
861 notmuch_database_mode_t mode,
862 notmuch_database_t **database,
863 char **status_string)
865 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
866 void *local = talloc_new (NULL);
867 notmuch_database_t *notmuch = NULL;
868 char *notmuch_path, *xapian_path, *incompat_features;
869 char *message = NULL;
872 unsigned int i, version;
873 static int initialized = 0;
876 message = strdup ("Error: Cannot open a database for a NULL path.\n");
877 status = NOTMUCH_STATUS_NULL_POINTER;
881 if (path[0] != '/') {
882 message = strdup ("Error: Database path must be absolute.\n");
883 status = NOTMUCH_STATUS_PATH_ERROR;
887 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
888 message = strdup ("Out of memory\n");
889 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
893 err = stat (notmuch_path, &st);
895 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
896 notmuch_path, strerror (errno)));
897 status = NOTMUCH_STATUS_FILE_ERROR;
901 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
902 message = strdup ("Out of memory\n");
903 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
907 /* Initialize the GLib type system and threads */
908 #if !GLIB_CHECK_VERSION(2, 35, 1)
912 /* Initialize gmime */
914 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
918 notmuch = talloc_zero (NULL, notmuch_database_t);
919 notmuch->exception_reported = FALSE;
920 notmuch->status_string = NULL;
921 notmuch->path = talloc_strdup (notmuch, path);
923 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
924 notmuch->path[strlen (notmuch->path) - 1] = '\0';
926 notmuch->mode = mode;
927 notmuch->atomic_nesting = 0;
929 string last_thread_id;
932 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
933 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
934 Xapian::DB_CREATE_OR_OPEN);
936 notmuch->xapian_db = new Xapian::Database (xapian_path);
939 /* Check version. As of database version 3, we represent
940 * changes in terms of features, so assume a version bump
941 * means a dramatically incompatible change. */
942 version = notmuch_database_get_version (notmuch);
943 if (version > NOTMUCH_DATABASE_VERSION) {
944 IGNORE_RESULT (asprintf (&message,
945 "Error: Notmuch database at %s\n"
946 " has a newer database format version (%u) than supported by this\n"
947 " version of notmuch (%u).\n",
948 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
949 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
950 notmuch_database_destroy (notmuch);
952 status = NOTMUCH_STATUS_FILE_ERROR;
956 /* Check features. */
957 incompat_features = NULL;
958 notmuch->features = _parse_features (
959 local, notmuch->xapian_db->get_metadata ("features").c_str (),
960 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
962 if (incompat_features) {
963 IGNORE_RESULT (asprintf (&message,
964 "Error: Notmuch database at %s\n"
965 " requires features (%s)\n"
966 " not supported by this version of notmuch.\n",
967 notmuch_path, incompat_features));
968 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
969 notmuch_database_destroy (notmuch);
971 status = NOTMUCH_STATUS_FILE_ERROR;
975 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
976 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
977 if (last_thread_id.empty ()) {
978 notmuch->last_thread_id = 0;
983 str = last_thread_id.c_str ();
984 notmuch->last_thread_id = strtoull (str, &end, 16);
986 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
989 /* Get current highest revision number. */
990 last_mod = notmuch->xapian_db->get_value_upper_bound (
991 NOTMUCH_VALUE_LAST_MOD);
992 if (last_mod.empty ())
993 notmuch->revision = 0;
995 notmuch->revision = Xapian::sortable_unserialise (last_mod);
996 notmuch->uuid = talloc_strdup (
997 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
999 notmuch->query_parser = new Xapian::QueryParser;
1000 notmuch->term_gen = new Xapian::TermGenerator;
1001 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1002 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1003 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1004 #if HAVE_XAPIAN_FIELD_PROCESSOR
1005 /* This currently relies on the query parser to pass anything
1006 * with a .. to the range processor */
1007 notmuch->date_field_processor = new DateFieldProcessor();
1008 notmuch->query_parser->add_boolean_prefix("date", notmuch->date_field_processor);
1009 notmuch->query_field_processor = new QueryFieldProcessor (*notmuch->query_parser, notmuch);
1010 notmuch->query_parser->add_boolean_prefix("query", notmuch->query_field_processor);
1012 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1014 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1015 notmuch->query_parser->set_database (*notmuch->xapian_db);
1016 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1017 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1018 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1019 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1020 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1022 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
1023 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
1024 notmuch->query_parser->add_boolean_prefix (prefix->name,
1028 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
1029 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
1030 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
1032 } catch (const Xapian::Error &error) {
1033 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1034 error.get_msg().c_str()));
1035 notmuch_database_destroy (notmuch);
1037 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1041 talloc_free (local);
1045 *status_string = message;
1051 *database = notmuch;
1053 talloc_free (notmuch);
1058 notmuch_database_close (notmuch_database_t *notmuch)
1060 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1062 /* Many Xapian objects (and thus notmuch objects) hold references to
1063 * the database, so merely deleting the database may not suffice to
1064 * close it. Thus, we explicitly close it here. */
1065 if (notmuch->xapian_db != NULL) {
1067 /* If there's an outstanding transaction, it's unclear if
1068 * closing the Xapian database commits everything up to
1069 * that transaction, or may discard committed (but
1070 * unflushed) transactions. To be certain, explicitly
1071 * cancel any outstanding transaction before closing. */
1072 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1073 notmuch->atomic_nesting)
1074 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1075 ->cancel_transaction ();
1077 /* Close the database. This implicitly flushes
1078 * outstanding changes. */
1079 notmuch->xapian_db->close();
1080 } catch (const Xapian::Error &error) {
1081 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1082 if (! notmuch->exception_reported) {
1083 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1084 error.get_msg().c_str());
1089 delete notmuch->term_gen;
1090 notmuch->term_gen = NULL;
1091 delete notmuch->query_parser;
1092 notmuch->query_parser = NULL;
1093 delete notmuch->xapian_db;
1094 notmuch->xapian_db = NULL;
1095 delete notmuch->value_range_processor;
1096 notmuch->value_range_processor = NULL;
1097 delete notmuch->date_range_processor;
1098 notmuch->date_range_processor = NULL;
1099 delete notmuch->last_mod_range_processor;
1100 notmuch->last_mod_range_processor = NULL;
1105 #if HAVE_XAPIAN_COMPACT
1107 unlink_cb (const char *path,
1108 unused (const struct stat *sb),
1110 unused (struct FTW *ftw))
1112 return remove (path);
1116 rmtree (const char *path)
1118 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1121 class NotmuchCompactor : public Xapian::Compactor
1123 notmuch_compact_status_cb_t status_cb;
1124 void *status_closure;
1127 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1128 status_cb (cb), status_closure (closure) { }
1131 set_status (const std::string &table, const std::string &status)
1135 if (status_cb == NULL)
1138 if (status.length () == 0)
1139 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1141 msg = talloc_asprintf (NULL, " %s", status.c_str());
1147 status_cb (msg, status_closure);
1152 /* Compacts the given database, optionally saving the original database
1153 * in backup_path. Additionally, a callback function can be provided to
1154 * give the user feedback on the progress of the (likely long-lived)
1155 * compaction process.
1157 * The backup path must point to a directory on the same volume as the
1158 * original database. Passing a NULL backup_path will result in the
1159 * uncompacted database being deleted after compaction has finished.
1160 * Note that the database write lock will be held during the
1161 * compaction process to protect data integrity.
1164 notmuch_database_compact (const char *path,
1165 const char *backup_path,
1166 notmuch_compact_status_cb_t status_cb,
1170 char *notmuch_path, *xapian_path, *compact_xapian_path;
1171 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1172 notmuch_database_t *notmuch = NULL;
1173 struct stat statbuf;
1174 notmuch_bool_t keep_backup;
1175 char *message = NULL;
1177 local = talloc_new (NULL);
1179 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1181 ret = notmuch_database_open_verbose (path,
1182 NOTMUCH_DATABASE_MODE_READ_WRITE,
1186 if (status_cb) status_cb (message, closure);
1190 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1191 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1195 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1196 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1200 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1201 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1205 if (backup_path == NULL) {
1206 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1207 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1210 keep_backup = FALSE;
1216 if (stat (backup_path, &statbuf) != -1) {
1217 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1218 ret = NOTMUCH_STATUS_FILE_ERROR;
1221 if (errno != ENOENT) {
1222 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1224 ret = NOTMUCH_STATUS_FILE_ERROR;
1228 /* Unconditionally attempt to remove old work-in-progress database (if
1229 * any). This is "protected" by database lock. If this fails due to write
1230 * errors (etc), the following code will fail and provide error message.
1232 (void) rmtree (compact_xapian_path);
1235 NotmuchCompactor compactor (status_cb, closure);
1237 compactor.set_renumber (false);
1238 compactor.add_source (xapian_path);
1239 compactor.set_destdir (compact_xapian_path);
1240 compactor.compact ();
1241 } catch (const Xapian::Error &error) {
1242 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1243 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1247 if (rename (xapian_path, backup_path)) {
1248 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1249 xapian_path, backup_path, strerror (errno));
1250 ret = NOTMUCH_STATUS_FILE_ERROR;
1254 if (rename (compact_xapian_path, xapian_path)) {
1255 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1256 compact_xapian_path, xapian_path, strerror (errno));
1257 ret = NOTMUCH_STATUS_FILE_ERROR;
1261 if (! keep_backup) {
1262 if (rmtree (backup_path)) {
1263 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1264 backup_path, strerror (errno));
1265 ret = NOTMUCH_STATUS_FILE_ERROR;
1272 notmuch_status_t ret2;
1274 const char *str = notmuch_database_status_string (notmuch);
1275 if (status_cb && str)
1276 status_cb (str, closure);
1278 ret2 = notmuch_database_destroy (notmuch);
1280 /* don't clobber previous error status */
1281 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1285 talloc_free (local);
1291 notmuch_database_compact (unused (const char *path),
1292 unused (const char *backup_path),
1293 unused (notmuch_compact_status_cb_t status_cb),
1294 unused (void *closure))
1296 _notmuch_database_log (notmuch, "notmuch was compiled against a xapian version lacking compaction support.\n");
1297 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1302 notmuch_database_destroy (notmuch_database_t *notmuch)
1304 notmuch_status_t status;
1306 status = notmuch_database_close (notmuch);
1307 talloc_free (notmuch);
1313 notmuch_database_get_path (notmuch_database_t *notmuch)
1315 return notmuch->path;
1319 notmuch_database_get_version (notmuch_database_t *notmuch)
1321 unsigned int version;
1322 string version_string;
1326 version_string = notmuch->xapian_db->get_metadata ("version");
1327 if (version_string.empty ())
1330 str = version_string.c_str ();
1331 if (str == NULL || *str == '\0')
1334 version = strtoul (str, &end, 10);
1336 INTERNAL_ERROR ("Malformed database version: %s", str);
1342 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1344 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1345 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1346 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1349 static volatile sig_atomic_t do_progress_notify = 0;
1352 handle_sigalrm (unused (int signal))
1354 do_progress_notify = 1;
1357 /* Upgrade the current database.
1359 * After opening a database in read-write mode, the client should
1360 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1361 * if so, upgrade with this function before making any modifications.
1363 * The optional progress_notify callback can be used by the caller to
1364 * provide progress indication to the user. If non-NULL it will be
1365 * called periodically with 'count' as the number of messages upgraded
1366 * so far and 'total' the overall number of messages that will be
1370 notmuch_database_upgrade (notmuch_database_t *notmuch,
1371 void (*progress_notify) (void *closure,
1375 void *local = talloc_new (NULL);
1376 Xapian::TermIterator t, t_end;
1377 Xapian::WritableDatabase *db;
1378 struct sigaction action;
1379 struct itimerval timerval;
1380 notmuch_bool_t timer_is_active = FALSE;
1381 enum _notmuch_features target_features, new_features;
1382 notmuch_status_t status;
1383 notmuch_private_status_t private_status;
1384 notmuch_query_t *query = NULL;
1385 unsigned int count = 0, total = 0;
1387 status = _notmuch_database_ensure_writable (notmuch);
1391 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1393 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1394 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1396 if (! notmuch_database_needs_upgrade (notmuch))
1397 return NOTMUCH_STATUS_SUCCESS;
1399 if (progress_notify) {
1400 /* Set up our handler for SIGALRM */
1401 memset (&action, 0, sizeof (struct sigaction));
1402 action.sa_handler = handle_sigalrm;
1403 sigemptyset (&action.sa_mask);
1404 action.sa_flags = SA_RESTART;
1405 sigaction (SIGALRM, &action, NULL);
1407 /* Then start a timer to send SIGALRM once per second. */
1408 timerval.it_interval.tv_sec = 1;
1409 timerval.it_interval.tv_usec = 0;
1410 timerval.it_value.tv_sec = 1;
1411 timerval.it_value.tv_usec = 0;
1412 setitimer (ITIMER_REAL, &timerval, NULL);
1414 timer_is_active = TRUE;
1417 /* Figure out how much total work we need to do. */
1419 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1420 NOTMUCH_FEATURE_LAST_MOD)) {
1421 query = notmuch_query_create (notmuch, "");
1424 status = notmuch_query_count_messages_st (query, &msg_count);
1429 notmuch_query_destroy (query);
1432 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1433 t_end = db->allterms_end ("XTIMESTAMP");
1434 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1437 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1438 /* The ghost message upgrade converts all thread_id_*
1439 * metadata values into ghost message documents. */
1440 t_end = db->metadata_keys_end ("thread_id_");
1441 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1445 /* Perform the upgrade in a transaction. */
1446 db->begin_transaction (true);
1448 /* Set the target features so we write out changes in the desired
1450 notmuch->features = target_features;
1452 /* Perform per-message upgrades. */
1454 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1455 NOTMUCH_FEATURE_LAST_MOD)) {
1456 notmuch_messages_t *messages;
1457 notmuch_message_t *message;
1460 query = notmuch_query_create (notmuch, "");
1462 status = notmuch_query_search_messages_st (query, &messages);
1466 notmuch_messages_valid (messages);
1467 notmuch_messages_move_to_next (messages))
1469 if (do_progress_notify) {
1470 progress_notify (closure, (double) count / total);
1471 do_progress_notify = 0;
1474 message = notmuch_messages_get (messages);
1476 /* Before version 1, each message document had its
1477 * filename in the data field. Copy that into the new
1478 * format by calling notmuch_message_add_filename.
1480 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1481 filename = _notmuch_message_talloc_copy_data (message);
1482 if (filename && *filename != '\0') {
1483 _notmuch_message_add_filename (message, filename);
1484 _notmuch_message_clear_data (message);
1486 talloc_free (filename);
1489 /* Prior to version 2, the "folder:" prefix was
1490 * probabilistic and stemmed. Change it to the current
1491 * boolean prefix. Add "path:" prefixes while at it.
1493 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1494 _notmuch_message_upgrade_folder (message);
1496 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1497 * track modification revisions. Give all messages the
1498 * next available revision; since we just started tracking
1499 * revisions for this database, that will be 1.
1501 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1502 _notmuch_message_upgrade_last_mod (message);
1504 _notmuch_message_sync (message);
1506 notmuch_message_destroy (message);
1511 notmuch_query_destroy (query);
1515 /* Perform per-directory upgrades. */
1517 /* Before version 1 we stored directory timestamps in
1518 * XTIMESTAMP documents instead of the current XDIRECTORY
1519 * documents. So copy those as well. */
1520 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1521 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1523 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1527 Xapian::PostingIterator p, p_end;
1528 std::string term = *t;
1530 p_end = notmuch->xapian_db->postlist_end (term);
1532 for (p = notmuch->xapian_db->postlist_begin (term);
1536 Xapian::Document document;
1538 notmuch_directory_t *directory;
1540 if (do_progress_notify) {
1541 progress_notify (closure, (double) count / total);
1542 do_progress_notify = 0;
1545 document = find_document_for_doc_id (notmuch, *p);
1546 mtime = Xapian::sortable_unserialise (
1547 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1549 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1550 NOTMUCH_FIND_CREATE, &status);
1551 notmuch_directory_set_mtime (directory, mtime);
1552 notmuch_directory_destroy (directory);
1554 db->delete_document (*p);
1561 /* Perform metadata upgrades. */
1563 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1564 * messages were stored as database metadata. Change these to
1567 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1568 notmuch_message_t *message;
1569 std::string message_id, thread_id;
1571 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1572 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1574 if (do_progress_notify) {
1575 progress_notify (closure, (double) count / total);
1576 do_progress_notify = 0;
1579 message_id = (*t).substr (
1580 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1581 thread_id = db->get_metadata (*t);
1583 /* Create ghost message */
1584 message = _notmuch_message_create_for_message_id (
1585 notmuch, message_id.c_str (), &private_status);
1586 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1587 /* Document already exists; ignore the stored thread ID */
1588 } else if (private_status ==
1589 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1590 private_status = _notmuch_message_initialize_ghost (
1591 message, thread_id.c_str ());
1592 if (! private_status)
1593 _notmuch_message_sync (message);
1596 if (private_status) {
1597 _notmuch_database_log (notmuch,
1598 "Upgrade failed while creating ghost messages.\n");
1599 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1603 /* Clear saved metadata thread ID */
1604 db->set_metadata (*t, "");
1610 status = NOTMUCH_STATUS_SUCCESS;
1611 db->set_metadata ("features", _print_features (local, notmuch->features));
1612 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1615 if (status == NOTMUCH_STATUS_SUCCESS)
1616 db->commit_transaction ();
1618 db->cancel_transaction ();
1620 if (timer_is_active) {
1621 /* Now stop the timer. */
1622 timerval.it_interval.tv_sec = 0;
1623 timerval.it_interval.tv_usec = 0;
1624 timerval.it_value.tv_sec = 0;
1625 timerval.it_value.tv_usec = 0;
1626 setitimer (ITIMER_REAL, &timerval, NULL);
1628 /* And disable the signal handler. */
1629 action.sa_handler = SIG_IGN;
1630 sigaction (SIGALRM, &action, NULL);
1634 notmuch_query_destroy (query);
1636 talloc_free (local);
1641 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1643 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1644 notmuch->atomic_nesting > 0)
1647 if (notmuch_database_needs_upgrade(notmuch))
1648 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1651 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1652 } catch (const Xapian::Error &error) {
1653 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1654 error.get_msg().c_str());
1655 notmuch->exception_reported = TRUE;
1656 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1660 notmuch->atomic_nesting++;
1661 return NOTMUCH_STATUS_SUCCESS;
1665 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1667 Xapian::WritableDatabase *db;
1669 if (notmuch->atomic_nesting == 0)
1670 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1672 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1673 notmuch->atomic_nesting > 1)
1676 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1678 db->commit_transaction ();
1680 /* This is a hack for testing. Xapian never flushes on a
1681 * non-flushed commit, even if the flush threshold is 1.
1682 * However, we rely on flushing to test atomicity. */
1683 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1684 if (thresh && atoi (thresh) == 1)
1686 } catch (const Xapian::Error &error) {
1687 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1688 error.get_msg().c_str());
1689 notmuch->exception_reported = TRUE;
1690 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1693 if (notmuch->atomic_dirty) {
1694 ++notmuch->revision;
1695 notmuch->atomic_dirty = FALSE;
1699 notmuch->atomic_nesting--;
1700 return NOTMUCH_STATUS_SUCCESS;
1704 notmuch_database_get_revision (notmuch_database_t *notmuch,
1708 *uuid = notmuch->uuid;
1709 return notmuch->revision;
1712 /* We allow the user to use arbitrarily long paths for directories. But
1713 * we have a term-length limit. So if we exceed that, we'll use the
1714 * SHA-1 of the path for the database term.
1716 * Note: This function may return the original value of 'path'. If it
1717 * does not, then the caller is responsible to free() the returned
1721 _notmuch_database_get_directory_db_path (const char *path)
1723 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1725 if (term_len > NOTMUCH_TERM_MAX)
1726 return _notmuch_sha1_of_string (path);
1731 /* Given a path, split it into two parts: the directory part is all
1732 * components except for the last, and the basename is that last
1733 * component. Getting the return-value for either part is optional
1734 * (the caller can pass NULL).
1736 * The original 'path' can represent either a regular file or a
1737 * directory---the splitting will be carried out in the same way in
1738 * either case. Trailing slashes on 'path' will be ignored, and any
1739 * cases of multiple '/' characters appearing in series will be
1740 * treated as a single '/'.
1742 * Allocation (if any) will have 'ctx' as the talloc owner. But
1743 * pointers will be returned within the original path string whenever
1746 * Note: If 'path' is non-empty and contains no non-trailing slash,
1747 * (that is, consists of a filename with no parent directory), then
1748 * the directory returned will be an empty string. However, if 'path'
1749 * is an empty string, then both directory and basename will be
1753 _notmuch_database_split_path (void *ctx,
1755 const char **directory,
1756 const char **basename)
1760 if (path == NULL || *path == '\0') {
1765 return NOTMUCH_STATUS_SUCCESS;
1768 /* Find the last slash (not counting a trailing slash), if any. */
1770 slash = path + strlen (path) - 1;
1772 /* First, skip trailing slashes. */
1773 while (slash != path && *slash == '/')
1776 /* Then, find a slash. */
1777 while (slash != path && *slash != '/') {
1784 /* Finally, skip multiple slashes. */
1785 while (slash != path && *(slash - 1) == '/')
1788 if (slash == path) {
1790 *directory = talloc_strdup (ctx, "");
1795 *directory = talloc_strndup (ctx, path, slash - path);
1798 return NOTMUCH_STATUS_SUCCESS;
1801 /* Find the document ID of the specified directory.
1803 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1804 * created if one does not exist for 'path'. Otherwise, if the
1805 * directory document does not exist, this sets *directory_id to
1806 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1809 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1811 notmuch_find_flags_t flags,
1812 unsigned int *directory_id)
1814 notmuch_directory_t *directory;
1815 notmuch_status_t status;
1819 return NOTMUCH_STATUS_SUCCESS;
1822 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1823 if (status || !directory) {
1828 *directory_id = _notmuch_directory_get_document_id (directory);
1830 notmuch_directory_destroy (directory);
1832 return NOTMUCH_STATUS_SUCCESS;
1836 _notmuch_database_get_directory_path (void *ctx,
1837 notmuch_database_t *notmuch,
1838 unsigned int doc_id)
1840 Xapian::Document document;
1842 document = find_document_for_doc_id (notmuch, doc_id);
1844 return talloc_strdup (ctx, document.get_data ().c_str ());
1847 /* Given a legal 'filename' for the database, (either relative to
1848 * database path or absolute with initial components identical to
1849 * database path), return a new string (with 'ctx' as the talloc
1850 * owner) suitable for use as a direntry term value.
1852 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1853 * will be created in the database as needed. Otherwise, if the
1854 * necessary directory documents do not exist, this sets
1855 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1858 _notmuch_database_filename_to_direntry (void *ctx,
1859 notmuch_database_t *notmuch,
1860 const char *filename,
1861 notmuch_find_flags_t flags,
1864 const char *relative, *directory, *basename;
1865 Xapian::docid directory_id;
1866 notmuch_status_t status;
1868 relative = _notmuch_database_relative_path (notmuch, filename);
1870 status = _notmuch_database_split_path (ctx, relative,
1871 &directory, &basename);
1875 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1877 if (status || directory_id == (unsigned int)-1) {
1882 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1884 return NOTMUCH_STATUS_SUCCESS;
1887 /* Given a legal 'path' for the database, return the relative path.
1889 * The return value will be a pointer to the original path contents,
1890 * and will be either the original string (if 'path' was relative) or
1891 * a portion of the string (if path was absolute and begins with the
1895 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1898 const char *db_path, *relative;
1899 unsigned int db_path_len;
1901 db_path = notmuch_database_get_path (notmuch);
1902 db_path_len = strlen (db_path);
1906 if (*relative == '/') {
1907 while (*relative == '/' && *(relative+1) == '/')
1910 if (strncmp (relative, db_path, db_path_len) == 0)
1912 relative += db_path_len;
1913 while (*relative == '/')
1922 notmuch_database_get_directory (notmuch_database_t *notmuch,
1924 notmuch_directory_t **directory)
1926 notmuch_status_t status;
1928 if (directory == NULL)
1929 return NOTMUCH_STATUS_NULL_POINTER;
1933 *directory = _notmuch_directory_create (notmuch, path,
1934 NOTMUCH_FIND_LOOKUP, &status);
1935 } catch (const Xapian::Error &error) {
1936 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1937 error.get_msg().c_str());
1938 notmuch->exception_reported = TRUE;
1939 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1944 /* Allocate a document ID that satisfies the following criteria:
1946 * 1. The ID does not exist for any document in the Xapian database
1948 * 2. The ID was not previously returned from this function
1950 * 3. The ID is the smallest integer satisfying (1) and (2)
1952 * This function will trigger an internal error if these constraints
1953 * cannot all be satisfied, (that is, the pool of available document
1954 * IDs has been exhausted).
1957 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1959 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1961 notmuch->last_doc_id++;
1963 if (notmuch->last_doc_id == 0)
1964 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1966 return notmuch->last_doc_id;
1970 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1972 /* 16 bytes (+ terminator) for hexadecimal representation of
1973 * a 64-bit integer. */
1974 static char thread_id[17];
1975 Xapian::WritableDatabase *db;
1977 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1979 notmuch->last_thread_id++;
1981 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1983 db->set_metadata ("last_thread_id", thread_id);
1989 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1991 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1992 message_id = _notmuch_message_id_compressed (ctx, message_id);
1994 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1998 static notmuch_status_t
1999 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2001 const char *message_id,
2002 const char **thread_id_ret);
2004 /* Find the thread ID to which the message with 'message_id' belongs.
2006 * Note: 'thread_id_ret' must not be NULL!
2007 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2010 * Note: If there is no message in the database with the given
2011 * 'message_id' then a new thread_id will be allocated for this
2012 * message ID and stored in the database metadata so that the
2013 * thread ID can be looked up if the message is added to the database
2016 static notmuch_status_t
2017 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2019 const char *message_id,
2020 const char **thread_id_ret)
2022 notmuch_private_status_t status;
2023 notmuch_message_t *message;
2025 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2026 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2029 /* Look for this message (regular or ghost) */
2030 message = _notmuch_message_create_for_message_id (
2031 notmuch, message_id, &status);
2032 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2033 /* Message exists */
2034 *thread_id_ret = talloc_steal (
2035 ctx, notmuch_message_get_thread_id (message));
2036 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2037 /* Message did not exist. Give it a fresh thread ID and
2038 * populate this message as a ghost message. */
2039 *thread_id_ret = talloc_strdup (
2040 ctx, _notmuch_database_generate_thread_id (notmuch));
2041 if (! *thread_id_ret) {
2042 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2044 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2046 /* Commit the new ghost message */
2047 _notmuch_message_sync (message);
2050 /* Create failed. Fall through. */
2053 notmuch_message_destroy (message);
2055 return COERCE_STATUS (status, "Error creating ghost message");
2058 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2059 static notmuch_status_t
2060 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2062 const char *message_id,
2063 const char **thread_id_ret)
2065 notmuch_status_t status;
2066 notmuch_message_t *message;
2067 string thread_id_string;
2069 Xapian::WritableDatabase *db;
2071 status = notmuch_database_find_message (notmuch, message_id, &message);
2077 *thread_id_ret = talloc_steal (ctx,
2078 notmuch_message_get_thread_id (message));
2080 notmuch_message_destroy (message);
2082 return NOTMUCH_STATUS_SUCCESS;
2085 /* Message has not been seen yet.
2087 * We may have seen a reference to it already, in which case, we
2088 * can return the thread ID stored in the metadata. Otherwise, we
2089 * generate a new thread ID and store it there.
2091 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2092 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2093 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2095 if (thread_id_string.empty()) {
2096 *thread_id_ret = talloc_strdup (ctx,
2097 _notmuch_database_generate_thread_id (notmuch));
2098 db->set_metadata (metadata_key, *thread_id_ret);
2100 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2103 talloc_free (metadata_key);
2105 return NOTMUCH_STATUS_SUCCESS;
2108 static notmuch_status_t
2109 _merge_threads (notmuch_database_t *notmuch,
2110 const char *winner_thread_id,
2111 const char *loser_thread_id)
2113 Xapian::PostingIterator loser, loser_end;
2114 notmuch_message_t *message = NULL;
2115 notmuch_private_status_t private_status;
2116 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2118 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2120 for ( ; loser != loser_end; loser++) {
2121 message = _notmuch_message_create (notmuch, notmuch,
2122 *loser, &private_status);
2123 if (message == NULL) {
2124 ret = COERCE_STATUS (private_status,
2125 "Cannot find document for doc_id from query");
2129 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2130 _notmuch_message_add_term (message, "thread", winner_thread_id);
2131 _notmuch_message_sync (message);
2133 notmuch_message_destroy (message);
2139 notmuch_message_destroy (message);
2145 _my_talloc_free_for_g_hash (void *ptr)
2150 static notmuch_status_t
2151 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2152 notmuch_message_t *message,
2153 notmuch_message_file_t *message_file,
2154 const char **thread_id)
2156 GHashTable *parents = NULL;
2157 const char *refs, *in_reply_to, *in_reply_to_message_id;
2158 const char *last_ref_message_id, *this_message_id;
2159 GList *l, *keys = NULL;
2160 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2162 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2163 _my_talloc_free_for_g_hash, NULL);
2164 this_message_id = notmuch_message_get_message_id (message);
2166 refs = _notmuch_message_file_get_header (message_file, "references");
2167 last_ref_message_id = parse_references (message,
2171 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2172 in_reply_to_message_id = parse_references (message,
2174 parents, in_reply_to);
2176 /* For the parent of this message, use the last message ID of the
2177 * References header, if available. If not, fall back to the
2178 * first message ID in the In-Reply-To header. */
2179 if (last_ref_message_id) {
2180 _notmuch_message_add_term (message, "replyto",
2181 last_ref_message_id);
2182 } else if (in_reply_to_message_id) {
2183 _notmuch_message_add_term (message, "replyto",
2184 in_reply_to_message_id);
2187 keys = g_hash_table_get_keys (parents);
2188 for (l = keys; l; l = l->next) {
2189 char *parent_message_id;
2190 const char *parent_thread_id = NULL;
2192 parent_message_id = (char *) l->data;
2194 _notmuch_message_add_term (message, "reference",
2197 ret = _resolve_message_id_to_thread_id (notmuch,
2204 if (*thread_id == NULL) {
2205 *thread_id = talloc_strdup (message, parent_thread_id);
2206 _notmuch_message_add_term (message, "thread", *thread_id);
2207 } else if (strcmp (*thread_id, parent_thread_id)) {
2208 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2218 g_hash_table_unref (parents);
2223 static notmuch_status_t
2224 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2225 notmuch_message_t *message,
2226 const char **thread_id)
2228 const char *message_id = notmuch_message_get_message_id (message);
2229 Xapian::PostingIterator child, children_end;
2230 notmuch_message_t *child_message = NULL;
2231 const char *child_thread_id;
2232 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2233 notmuch_private_status_t private_status;
2235 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2237 for ( ; child != children_end; child++) {
2239 child_message = _notmuch_message_create (message, notmuch,
2240 *child, &private_status);
2241 if (child_message == NULL) {
2242 ret = COERCE_STATUS (private_status,
2243 "Cannot find document for doc_id from query");
2247 child_thread_id = notmuch_message_get_thread_id (child_message);
2248 if (*thread_id == NULL) {
2249 *thread_id = talloc_strdup (message, child_thread_id);
2250 _notmuch_message_add_term (message, "thread", *thread_id);
2251 } else if (strcmp (*thread_id, child_thread_id)) {
2252 _notmuch_message_remove_term (child_message, "reference",
2254 _notmuch_message_sync (child_message);
2255 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2260 notmuch_message_destroy (child_message);
2261 child_message = NULL;
2266 notmuch_message_destroy (child_message);
2271 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2273 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2274 notmuch_message_t *message)
2276 const char *message_id;
2280 message_id = notmuch_message_get_message_id (message);
2281 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2283 /* Check if we have already seen related messages to this one.
2284 * If we have then use the thread_id that we stored at that time.
2286 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2287 if (stored_id.empty ()) {
2290 Xapian::WritableDatabase *db;
2292 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2294 /* Clear the metadata for this message ID. We don't need it
2296 db->set_metadata (metadata_key, "");
2298 return talloc_strdup (ctx, stored_id.c_str ());
2302 /* Given a blank or ghost 'message' and its corresponding
2303 * 'message_file' link it to existing threads in the database.
2305 * First, if is_ghost, this retrieves the thread ID already stored in
2306 * the message (which will be the case if a message was previously
2307 * added that referenced this one). If the message is blank
2308 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2309 * later in this function). If the database does not support ghost
2310 * messages, this checks for a thread ID stored in database metadata
2311 * for this message ID.
2313 * Second, we look at 'message_file' and its link-relevant headers
2314 * (References and In-Reply-To) for message IDs.
2316 * Finally, we look in the database for existing message that
2317 * reference 'message'.
2319 * In all cases, we assign to the current message the first thread ID
2320 * found. We will also merge any existing, distinct threads where this
2321 * message belongs to both, (which is not uncommon when messages are
2322 * processed out of order).
2324 * Finally, if no thread ID has been found through referenced messages, we
2325 * call _notmuch_message_generate_thread_id to generate a new thread
2326 * ID. This should only happen for new, top-level messages, (no
2327 * References or In-Reply-To header in this message, and no previously
2328 * added message refers to this message).
2330 static notmuch_status_t
2331 _notmuch_database_link_message (notmuch_database_t *notmuch,
2332 notmuch_message_t *message,
2333 notmuch_message_file_t *message_file,
2334 notmuch_bool_t is_ghost)
2336 void *local = talloc_new (NULL);
2337 notmuch_status_t status;
2338 const char *thread_id = NULL;
2340 /* Check if the message already had a thread ID */
2341 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2343 thread_id = notmuch_message_get_thread_id (message);
2345 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2347 _notmuch_message_add_term (message, "thread", thread_id);
2350 status = _notmuch_database_link_message_to_parents (notmuch, message,
2356 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2357 /* In general, it shouldn't be necessary to link children,
2358 * since the earlier indexing of those children will have
2359 * stored a thread ID for the missing parent. However, prior
2360 * to ghost messages, these stored thread IDs were NOT
2361 * rewritten during thread merging (and there was no
2362 * performant way to do so), so if indexed children were
2363 * pulled into a different thread ID by a merge, it was
2364 * necessary to pull them *back* into the stored thread ID of
2365 * the parent. With ghost messages, we just rewrite the
2366 * stored thread IDs during merging, so this workaround isn't
2368 status = _notmuch_database_link_message_to_children (notmuch, message,
2374 /* If not part of any existing thread, generate a new thread ID. */
2375 if (thread_id == NULL) {
2376 thread_id = _notmuch_database_generate_thread_id (notmuch);
2378 _notmuch_message_add_term (message, "thread", thread_id);
2382 talloc_free (local);
2388 notmuch_database_add_message (notmuch_database_t *notmuch,
2389 const char *filename,
2390 notmuch_message_t **message_ret)
2392 notmuch_message_file_t *message_file;
2393 notmuch_message_t *message = NULL;
2394 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2395 notmuch_private_status_t private_status;
2396 notmuch_bool_t is_ghost = false;
2398 const char *date, *header;
2399 const char *from, *to, *subject;
2400 char *message_id = NULL;
2403 *message_ret = NULL;
2405 ret = _notmuch_database_ensure_writable (notmuch);
2409 message_file = _notmuch_message_file_open (notmuch, filename);
2410 if (message_file == NULL)
2411 return NOTMUCH_STATUS_FILE_ERROR;
2413 /* Adding a message may change many documents. Do this all
2415 ret = notmuch_database_begin_atomic (notmuch);
2419 /* Parse message up front to get better error status. */
2420 ret = _notmuch_message_file_parse (message_file);
2425 /* Before we do any real work, (especially before doing a
2426 * potential SHA-1 computation on the entire file's contents),
2427 * let's make sure that what we're looking at looks like an
2428 * actual email message.
2430 from = _notmuch_message_file_get_header (message_file, "from");
2431 subject = _notmuch_message_file_get_header (message_file, "subject");
2432 to = _notmuch_message_file_get_header (message_file, "to");
2434 if ((from == NULL || *from == '\0') &&
2435 (subject == NULL || *subject == '\0') &&
2436 (to == NULL || *to == '\0'))
2438 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2442 /* Now that we're sure it's mail, the first order of business
2443 * is to find a message ID (or else create one ourselves). */
2445 header = _notmuch_message_file_get_header (message_file, "message-id");
2446 if (header && *header != '\0') {
2447 message_id = _parse_message_id (message_file, header, NULL);
2449 /* So the header value isn't RFC-compliant, but it's
2450 * better than no message-id at all. */
2451 if (message_id == NULL)
2452 message_id = talloc_strdup (message_file, header);
2455 if (message_id == NULL ) {
2456 /* No message-id at all, let's generate one by taking a
2457 * hash over the file's contents. */
2458 char *sha1 = _notmuch_sha1_of_file (filename);
2460 /* If that failed too, something is really wrong. Give up. */
2462 ret = NOTMUCH_STATUS_FILE_ERROR;
2466 message_id = talloc_asprintf (message_file,
2467 "notmuch-sha1-%s", sha1);
2471 /* Now that we have a message ID, we get a message object,
2472 * (which may or may not reference an existing document in the
2475 message = _notmuch_message_create_for_message_id (notmuch,
2479 talloc_free (message_id);
2481 if (message == NULL) {
2482 ret = COERCE_STATUS (private_status,
2483 "Unexpected status value from _notmuch_message_create_for_message_id");
2487 _notmuch_message_add_filename (message, filename);
2489 /* Is this a newly created message object or a ghost
2490 * message? We have to be slightly careful: if this is a
2491 * blank message, it's not safe to call
2492 * notmuch_message_get_flag yet. */
2493 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2494 (is_ghost = notmuch_message_get_flag (
2495 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2496 _notmuch_message_add_term (message, "type", "mail");
2498 /* Convert ghost message to a regular message */
2499 _notmuch_message_remove_term (message, "type", "ghost");
2501 ret = _notmuch_database_link_message (notmuch, message,
2502 message_file, is_ghost);
2506 date = _notmuch_message_file_get_header (message_file, "date");
2507 _notmuch_message_set_header_values (message, date, from, subject);
2509 ret = _notmuch_message_index_file (message, message_file);
2513 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2516 _notmuch_message_sync (message);
2517 } catch (const Xapian::Error &error) {
2518 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2519 error.get_msg().c_str());
2520 notmuch->exception_reported = TRUE;
2521 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2527 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2528 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2529 *message_ret = message;
2531 notmuch_message_destroy (message);
2535 _notmuch_message_file_close (message_file);
2537 ret2 = notmuch_database_end_atomic (notmuch);
2538 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2539 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2540 ret2 != NOTMUCH_STATUS_SUCCESS)
2547 notmuch_database_remove_message (notmuch_database_t *notmuch,
2548 const char *filename)
2550 notmuch_status_t status;
2551 notmuch_message_t *message;
2553 status = notmuch_database_find_message_by_filename (notmuch, filename,
2556 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2557 status = _notmuch_message_remove_filename (message, filename);
2558 if (status == NOTMUCH_STATUS_SUCCESS)
2559 _notmuch_message_delete (message);
2560 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2561 _notmuch_message_sync (message);
2563 notmuch_message_destroy (message);
2570 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2571 const char *filename,
2572 notmuch_message_t **message_ret)
2575 const char *prefix = _find_prefix ("file-direntry");
2576 char *direntry, *term;
2577 Xapian::PostingIterator i, end;
2578 notmuch_status_t status;
2580 if (message_ret == NULL)
2581 return NOTMUCH_STATUS_NULL_POINTER;
2583 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2584 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2586 /* return NULL on any failure */
2587 *message_ret = NULL;
2589 local = talloc_new (notmuch);
2592 status = _notmuch_database_filename_to_direntry (
2593 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2594 if (status || !direntry)
2597 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2599 find_doc_ids_for_term (notmuch, term, &i, &end);
2602 notmuch_private_status_t private_status;
2604 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2606 if (*message_ret == NULL)
2607 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2609 } catch (const Xapian::Error &error) {
2610 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2611 error.get_msg().c_str());
2612 notmuch->exception_reported = TRUE;
2613 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2617 talloc_free (local);
2619 if (status && *message_ret) {
2620 notmuch_message_destroy (*message_ret);
2621 *message_ret = NULL;
2626 notmuch_string_list_t *
2627 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2628 Xapian::TermIterator &end,
2631 int prefix_len = strlen (prefix);
2632 notmuch_string_list_t *list;
2634 list = _notmuch_string_list_create (ctx);
2635 if (unlikely (list == NULL))
2638 for (i.skip_to (prefix); i != end; i++) {
2639 /* Terminate loop at first term without desired prefix. */
2640 if (strncmp ((*i).c_str (), prefix, prefix_len))
2643 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2650 notmuch_database_get_all_tags (notmuch_database_t *db)
2652 Xapian::TermIterator i, end;
2653 notmuch_string_list_t *tags;
2656 i = db->xapian_db->allterms_begin();
2657 end = db->xapian_db->allterms_end();
2658 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2659 _find_prefix ("tag"));
2660 _notmuch_string_list_sort (tags);
2661 return _notmuch_tags_create (db, tags);
2662 } catch (const Xapian::Error &error) {
2663 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2664 error.get_msg().c_str());
2665 db->exception_reported = TRUE;
2671 notmuch_database_status_string (const notmuch_database_t *notmuch)
2673 return notmuch->status_string;