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 https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "thread-fp.h"
25 #include "regexp-fields.h"
26 #include "string-util.h"
35 #include <glib.h> /* g_free, GPtrArray, GHashTable */
36 #include <glib-object.h> /* g_type_init */
38 #include <gmime/gmime.h> /* g_mime_init */
42 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
47 notmuch_field_flag_t flags;
50 #define NOTMUCH_DATABASE_VERSION 3
52 #define STRINGIFY(s) _SUB_STRINGIFY(s)
53 #define _SUB_STRINGIFY(s) #s
55 #if HAVE_XAPIAN_DB_RETRY_LOCK
56 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
58 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
61 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
63 * We currently have three different types of documents (mail, ghost,
64 * and directory) and also some metadata.
68 * A mail document is associated with a particular email message. It
69 * is stored in one or more files on disk (though only one has its
70 * content indexed) and is uniquely identified by its "id" field
71 * (which is generally the message ID). It is indexed with the
72 * following prefixed terms which the database uses to construct
75 * Single terms of given prefix:
79 * id: Unique ID of mail. This is from the Message-ID header
80 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
81 * If it's present and too long, then we use
82 * "notmuch-sha1-<sha1_sum_of_message_id>".
83 * If this header is not present, we use
84 * "notmuch-sha1-<sha1_sum_of_entire_file>".
86 * thread: The ID of the thread to which the mail belongs
88 * replyto: The ID from the In-Reply-To header of the mail (if any).
90 * Multiple terms of given prefix:
92 * reference: All message IDs from In-Reply-To and References
93 * headers in the message.
95 * tag: Any tags associated with this message by the user.
97 * file-direntry: A colon-separated pair of values
98 * (INTEGER:STRING), where INTEGER is the
99 * document ID of a directory document, and
100 * STRING is the name of a file within that
101 * directory for this mail message.
103 * property: Has a property with key=value
104 * FIXME: if no = is present, should match on any value
106 * A mail document also has four values:
108 * TIMESTAMP: The time_t value corresponding to the message's
111 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
113 * FROM: The value of the "From" header
115 * SUBJECT: The value of the "Subject" header
117 * LAST_MOD: The revision number as of the last tag or
120 * In addition, terms from the content of the message are added with
121 * "from", "to", "attachment", and "subject" prefixes for use by the
122 * user in searching. Similarly, terms from the path of the mail
123 * message are added with "folder" and "path" prefixes. But the
124 * database doesn't really care itself about any of these.
126 * The data portion of a mail document is empty.
128 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
129 * -----------------------------------------------
130 * A ghost mail document is like a mail document, but where we don't
131 * have the message content. These are used to track thread reference
132 * information for messages we haven't received.
134 * A ghost mail document has type: ghost; id and thread fields that
135 * are identical to the mail document fields; and a MESSAGE_ID value.
139 * A directory document is used by a client of the notmuch library to
140 * maintain data necessary to allow for efficient polling of mail
143 * All directory documents contain one term:
145 * directory: The directory path (relative to the database path)
146 * Or the SHA1 sum of the directory path (if the
147 * path itself is too long to fit in a Xapian
150 * And all directory documents for directories other than top-level
151 * directories also contain the following term:
153 * directory-direntry: A colon-separated pair of values
154 * (INTEGER:STRING), where INTEGER is the
155 * document ID of the parent directory
156 * document, and STRING is the name of this
157 * directory within that parent.
159 * All directory documents have a single value:
161 * TIMESTAMP: The mtime of the directory (at last scan)
163 * The data portion of a directory document contains the path of the
164 * directory (relative to the database path).
168 * Xapian allows us to store arbitrary name-value pairs as
169 * "metadata". We currently use the following metadata names with the
172 * version The database schema version, (which is distinct
173 * from both the notmuch package version (see
174 * notmuch --version) and the libnotmuch library
175 * version. The version is stored as an base-10
176 * ASCII integer. The initial database version
177 * was 1, (though a schema existed before that
178 * were no "version" database value existed at
179 * all). Successive versions are allocated as
180 * changes are made to the database (such as by
181 * indexing new fields).
183 * features The set of features supported by this
184 * database. This consists of a set of
185 * '\n'-separated lines, where each is a feature
186 * name, a '\t', and compatibility flags. If the
187 * compatibility flags contain 'w', then the
188 * opener must support this feature to safely
189 * write this database. If the compatibility
190 * flags contain 'r', then the opener must
191 * support this feature to read this database.
192 * Introduced in database version 3.
194 * last_thread_id The last thread ID generated. This is stored
195 * as a 16-byte hexadecimal ASCII representation
196 * of a 64-bit unsigned integer. The first ID
197 * generated is 1 and the value will be
198 * incremented for each thread ID.
200 * C* metadata keys starting with C indicate
201 * configuration data. It can be managed with the
202 * n_database_*config* API. There is a convention
203 * of hierarchical keys separated by '.' (e.g.
204 * query.notmuch stores the value for the named
205 * query 'notmuch'), but it is not enforced by the
211 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
212 * Instead, the database has the following additional database
215 * thread_id_* A pre-allocated thread ID for a particular
216 * message. This is actually an arbitrarily large
217 * family of metadata name. Any particular name is
218 * formed by concatenating "thread_id_" with a message
219 * ID (or the SHA1 sum of a message ID if it is very
220 * long---see description of 'id' in the mail
221 * document). The value stored is a thread ID.
223 * These thread ID metadata values are stored
224 * whenever a message references a parent message
225 * that does not yet exist in the database. A
226 * thread ID will be allocated and stored, and if
227 * the message is later added, the stored thread
228 * ID will be used (and the metadata value will
231 * Even before a message is added, it's
232 * pre-allocated thread ID is useful so that all
233 * descendant messages that reference this common
234 * parent can be recognized as belonging to the
238 /* With these prefix values we follow the conventions published here:
240 * https://xapian.org/docs/omega/termprefixes.html
242 * as much as makes sense. Note that I took some liberty in matching
243 * the reserved prefix values to notmuch concepts, (for example, 'G'
244 * is documented as "newsGroup (or similar entity - e.g. a web forum
245 * name)", for which I think the thread is the closest analogue in
246 * notmuch. This in spite of the fact that we will eventually be
247 * storing mailing-list messages where 'G' for "mailing list name"
248 * might be even a closer analogue. I'm treating the single-character
249 * prefixes preferentially for core notmuch concepts (which will be
250 * nearly universal to all mail messages).
254 prefix_t prefix_table[] = {
255 /* name term prefix flags */
256 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
257 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
258 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
259 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
260 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
261 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
262 { "thread", "G", NOTMUCH_FIELD_EXTERNAL |
263 NOTMUCH_FIELD_PROCESSOR },
264 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
265 NOTMUCH_FIELD_PROCESSOR },
266 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
267 NOTMUCH_FIELD_PROCESSOR },
268 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
269 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
270 NOTMUCH_FIELD_PROCESSOR },
271 { "path", "P", NOTMUCH_FIELD_EXTERNAL|
272 NOTMUCH_FIELD_PROCESSOR },
273 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
275 * Unconditionally add ':' to reduce potential ambiguity with
276 * overlapping prefixes and/or terms that start with capital
277 * letters. See Xapian document termprefixes.html for related
280 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
281 NOTMUCH_FIELD_PROCESSOR },
282 #if HAVE_XAPIAN_FIELD_PROCESSOR
283 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
284 NOTMUCH_FIELD_PROCESSOR },
285 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
286 NOTMUCH_FIELD_PROCESSOR },
288 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
289 NOTMUCH_FIELD_PROBABILISTIC |
290 NOTMUCH_FIELD_PROCESSOR },
291 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
292 NOTMUCH_FIELD_PROBABILISTIC },
293 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
294 NOTMUCH_FIELD_PROBABILISTIC },
295 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
296 NOTMUCH_FIELD_PROBABILISTIC },
297 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
298 NOTMUCH_FIELD_PROBABILISTIC |
299 NOTMUCH_FIELD_PROCESSOR},
303 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
305 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
306 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
308 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
311 #if HAVE_XAPIAN_FIELD_PROCESSOR
313 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
315 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
316 Xapian::FieldProcessor *fp;
318 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
319 fp = (new DateFieldProcessor())->release ();
320 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
321 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
322 else if (STRNCMP_LITERAL(prefix->name, "thread") == 0)
323 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
325 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
326 *notmuch->query_parser, notmuch))->release ();
328 /* we treat all field-processor fields as boolean in order to get the raw input */
329 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
331 _setup_query_field_default (prefix, notmuch);
336 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
338 _setup_query_field_default (prefix, notmuch);
343 _find_prefix (const char *name)
347 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
348 if (strcmp (name, prefix_table[i].name) == 0)
349 return prefix_table[i].prefix;
352 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
357 static const struct {
358 /* NOTMUCH_FEATURE_* value. */
359 _notmuch_features value;
360 /* Feature name as it appears in the database. This name should
361 * be appropriate for displaying to the user if an older version
362 * of notmuch doesn't support this feature. */
364 /* Compatibility flags when this feature is declared. */
366 } feature_names[] = {
367 { NOTMUCH_FEATURE_FILE_TERMS,
368 "multiple paths per message", "rw" },
369 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
370 "relative directory paths", "rw" },
371 /* Header values are not required for reading a database because a
372 * reader can just refer to the message file. */
373 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
374 "from/subject/message-ID in database", "w" },
375 { NOTMUCH_FEATURE_BOOL_FOLDER,
376 "exact folder:/path: search", "rw" },
377 { NOTMUCH_FEATURE_GHOSTS,
378 "mail documents for missing messages", "w"},
379 /* Knowledge of the index mime-types are not required for reading
380 * a database because a reader will just be unable to query
382 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
383 "indexed MIME types", "w"},
384 { NOTMUCH_FEATURE_LAST_MOD,
385 "modification tracking", "w"},
389 notmuch_status_to_string (notmuch_status_t status)
392 case NOTMUCH_STATUS_SUCCESS:
393 return "No error occurred";
394 case NOTMUCH_STATUS_OUT_OF_MEMORY:
395 return "Out of memory";
396 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
397 return "Attempt to write to a read-only database";
398 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
399 return "A Xapian exception occurred";
400 case NOTMUCH_STATUS_FILE_ERROR:
401 return "Something went wrong trying to read or write a file";
402 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
403 return "File is not an email";
404 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
405 return "Message ID is identical to a message in database";
406 case NOTMUCH_STATUS_NULL_POINTER:
407 return "Erroneous NULL pointer";
408 case NOTMUCH_STATUS_TAG_TOO_LONG:
409 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
410 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
411 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
412 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
413 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
414 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
415 return "Unsupported operation";
416 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
417 return "Operation requires a database upgrade";
418 case NOTMUCH_STATUS_PATH_ERROR:
419 return "Path supplied is illegal for this function";
420 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
421 return "Crypto protocol missing, malformed, or unintelligible";
422 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
423 return "Crypto engine initialization failure";
424 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
425 return "Unknown crypto protocol";
427 case NOTMUCH_STATUS_LAST_STATUS:
428 return "Unknown error status value";
433 _notmuch_database_log (notmuch_database_t *notmuch,
439 va_start (va_args, format);
441 if (notmuch->status_string)
442 talloc_free (notmuch->status_string);
444 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
449 _notmuch_database_log_append (notmuch_database_t *notmuch,
455 va_start (va_args, format);
457 if (notmuch->status_string)
458 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
460 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
466 find_doc_ids_for_term (notmuch_database_t *notmuch,
468 Xapian::PostingIterator *begin,
469 Xapian::PostingIterator *end)
471 *begin = notmuch->xapian_db->postlist_begin (term);
473 *end = notmuch->xapian_db->postlist_end (term);
477 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
478 const char *prefix_name,
480 Xapian::PostingIterator *begin,
481 Xapian::PostingIterator *end)
485 term = talloc_asprintf (notmuch, "%s%s",
486 _find_prefix (prefix_name), value);
488 find_doc_ids_for_term (notmuch, term, begin, end);
493 notmuch_private_status_t
494 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
495 const char *prefix_name,
497 unsigned int *doc_id)
499 Xapian::PostingIterator i, end;
501 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
505 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
510 #if DEBUG_DATABASE_SANITY
514 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
518 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
521 static Xapian::Document
522 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
524 return notmuch->xapian_db->get_document (doc_id);
527 /* Generate a compressed version of 'message_id' of the form:
529 * notmuch-sha1-<sha1_sum_of_message_id>
532 _notmuch_message_id_compressed (void *ctx, const char *message_id)
534 char *sha1, *compressed;
536 sha1 = _notmuch_sha1_of_string (message_id);
538 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
545 notmuch_database_find_message (notmuch_database_t *notmuch,
546 const char *message_id,
547 notmuch_message_t **message_ret)
549 notmuch_private_status_t status;
552 if (message_ret == NULL)
553 return NOTMUCH_STATUS_NULL_POINTER;
555 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
556 message_id = _notmuch_message_id_compressed (notmuch, message_id);
559 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
560 message_id, &doc_id);
562 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
565 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
567 if (*message_ret == NULL)
568 return NOTMUCH_STATUS_OUT_OF_MEMORY;
571 return NOTMUCH_STATUS_SUCCESS;
572 } catch (const Xapian::Error &error) {
573 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
574 error.get_msg().c_str());
575 notmuch->exception_reported = true;
577 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
582 notmuch_database_create (const char *path, notmuch_database_t **database)
584 char *status_string = NULL;
585 notmuch_status_t status;
587 status = notmuch_database_create_verbose (path, database,
591 fputs (status_string, stderr);
592 free (status_string);
599 notmuch_database_create_verbose (const char *path,
600 notmuch_database_t **database,
601 char **status_string)
603 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
604 notmuch_database_t *notmuch = NULL;
605 char *notmuch_path = NULL;
606 char *message = NULL;
611 message = strdup ("Error: Cannot create a database for a NULL path.\n");
612 status = NOTMUCH_STATUS_NULL_POINTER;
616 if (path[0] != '/') {
617 message = strdup ("Error: Database path must be absolute.\n");
618 status = NOTMUCH_STATUS_PATH_ERROR;
622 err = stat (path, &st);
624 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
625 path, strerror (errno)));
626 status = NOTMUCH_STATUS_FILE_ERROR;
630 if (! S_ISDIR (st.st_mode)) {
631 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
632 "Not a directory.\n",
634 status = NOTMUCH_STATUS_FILE_ERROR;
638 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
640 err = mkdir (notmuch_path, 0755);
643 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
644 notmuch_path, strerror (errno)));
645 status = NOTMUCH_STATUS_FILE_ERROR;
649 status = notmuch_database_open_verbose (path,
650 NOTMUCH_DATABASE_MODE_READ_WRITE,
655 /* Upgrade doesn't add these feature to existing databases, but
656 * new databases have them. */
657 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
658 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
660 status = notmuch_database_upgrade (notmuch, NULL, NULL);
662 notmuch_database_close(notmuch);
668 talloc_free (notmuch_path);
672 *status_string = message;
679 talloc_free (notmuch);
684 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
686 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
687 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
688 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
691 return NOTMUCH_STATUS_SUCCESS;
694 /* Allocate a revision number for the next change. */
696 _notmuch_database_new_revision (notmuch_database_t *notmuch)
698 unsigned long new_revision = notmuch->revision + 1;
700 /* If we're in an atomic section, hold off on updating the
701 * committed revision number until we commit the atomic section.
703 if (notmuch->atomic_nesting)
704 notmuch->atomic_dirty = true;
706 notmuch->revision = new_revision;
711 /* Parse a database features string from the given database version.
712 * Returns the feature bit set.
714 * For version < 3, this ignores the features string and returns a
715 * hard-coded set of features.
717 * If there are unrecognized features that are required to open the
718 * database in mode (which should be 'r' or 'w'), return a
719 * comma-separated list of unrecognized but required features in
720 * *incompat_out suitable for presenting to the user. *incompat_out
721 * will be allocated from ctx.
723 static _notmuch_features
724 _parse_features (const void *ctx, const char *features, unsigned int version,
725 char mode, char **incompat_out)
727 _notmuch_features res = static_cast<_notmuch_features>(0);
728 unsigned int namelen, i;
732 /* Prior to database version 3, features were implied by the
735 return NOTMUCH_FEATURES_V0;
736 else if (version == 1)
737 return NOTMUCH_FEATURES_V1;
738 else if (version == 2)
739 return NOTMUCH_FEATURES_V2;
741 /* Parse the features string */
742 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
743 flags = strchr (features, '\t');
744 if (! flags || flags > features + llen)
746 namelen = flags - features;
748 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
749 if (strlen (feature_names[i].name) == namelen &&
750 strncmp (feature_names[i].name, features, namelen) == 0) {
751 res |= feature_names[i].value;
756 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
757 /* Unrecognized feature */
758 const char *have = strchr (flags, mode);
759 if (have && have < features + llen) {
760 /* This feature is required to access this database in
761 * 'mode', but we don't understand it. */
763 *incompat_out = talloc_strdup (ctx, "");
764 *incompat_out = talloc_asprintf_append_buffer (
765 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
775 _print_features (const void *ctx, unsigned int features)
778 char *res = talloc_strdup (ctx, "");
780 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
781 if (features & feature_names[i].value)
782 res = talloc_asprintf_append_buffer (
783 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
789 notmuch_database_open (const char *path,
790 notmuch_database_mode_t mode,
791 notmuch_database_t **database)
793 char *status_string = NULL;
794 notmuch_status_t status;
796 status = notmuch_database_open_verbose (path, mode, database,
800 fputs (status_string, stderr);
801 free (status_string);
808 notmuch_database_open_verbose (const char *path,
809 notmuch_database_mode_t mode,
810 notmuch_database_t **database,
811 char **status_string)
813 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
814 void *local = talloc_new (NULL);
815 notmuch_database_t *notmuch = NULL;
816 char *notmuch_path, *xapian_path, *incompat_features;
817 char *message = NULL;
820 unsigned int i, version;
821 static int initialized = 0;
824 message = strdup ("Error: Cannot open a database for a NULL path.\n");
825 status = NOTMUCH_STATUS_NULL_POINTER;
829 if (path[0] != '/') {
830 message = strdup ("Error: Database path must be absolute.\n");
831 status = NOTMUCH_STATUS_PATH_ERROR;
835 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
836 message = strdup ("Out of memory\n");
837 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
841 err = stat (notmuch_path, &st);
843 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
844 notmuch_path, strerror (errno)));
845 status = NOTMUCH_STATUS_FILE_ERROR;
849 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
850 message = strdup ("Out of memory\n");
851 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
855 /* Initialize the GLib type system and threads */
856 #if !GLIB_CHECK_VERSION(2, 35, 1)
860 /* Initialize gmime */
862 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
866 notmuch = talloc_zero (NULL, notmuch_database_t);
867 notmuch->exception_reported = false;
868 notmuch->status_string = NULL;
869 notmuch->path = talloc_strdup (notmuch, path);
871 strip_trailing(notmuch->path, '/');
873 notmuch->mode = mode;
874 notmuch->atomic_nesting = 0;
877 string last_thread_id;
880 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
881 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
884 notmuch->xapian_db = new Xapian::Database (xapian_path);
887 /* Check version. As of database version 3, we represent
888 * changes in terms of features, so assume a version bump
889 * means a dramatically incompatible change. */
890 version = notmuch_database_get_version (notmuch);
891 if (version > NOTMUCH_DATABASE_VERSION) {
892 IGNORE_RESULT (asprintf (&message,
893 "Error: Notmuch database at %s\n"
894 " has a newer database format version (%u) than supported by this\n"
895 " version of notmuch (%u).\n",
896 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
897 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
898 notmuch_database_destroy (notmuch);
900 status = NOTMUCH_STATUS_FILE_ERROR;
904 /* Check features. */
905 incompat_features = NULL;
906 notmuch->features = _parse_features (
907 local, notmuch->xapian_db->get_metadata ("features").c_str (),
908 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
910 if (incompat_features) {
911 IGNORE_RESULT (asprintf (&message,
912 "Error: Notmuch database at %s\n"
913 " requires features (%s)\n"
914 " not supported by this version of notmuch.\n",
915 notmuch_path, incompat_features));
916 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
917 notmuch_database_destroy (notmuch);
919 status = NOTMUCH_STATUS_FILE_ERROR;
923 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
924 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
925 if (last_thread_id.empty ()) {
926 notmuch->last_thread_id = 0;
931 str = last_thread_id.c_str ();
932 notmuch->last_thread_id = strtoull (str, &end, 16);
934 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
937 /* Get current highest revision number. */
938 last_mod = notmuch->xapian_db->get_value_upper_bound (
939 NOTMUCH_VALUE_LAST_MOD);
940 if (last_mod.empty ())
941 notmuch->revision = 0;
943 notmuch->revision = Xapian::sortable_unserialise (last_mod);
944 notmuch->uuid = talloc_strdup (
945 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
947 notmuch->query_parser = new Xapian::QueryParser;
948 notmuch->term_gen = new Xapian::TermGenerator;
949 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
950 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
951 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
952 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
954 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
955 notmuch->query_parser->set_database (*notmuch->xapian_db);
956 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
957 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
958 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
959 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
960 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
962 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
963 const prefix_t *prefix = &prefix_table[i];
964 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
965 _setup_query_field (prefix, notmuch);
968 } catch (const Xapian::Error &error) {
969 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
970 error.get_msg().c_str()));
971 notmuch_database_destroy (notmuch);
973 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
981 *status_string = message;
989 talloc_free (notmuch);
994 notmuch_database_close (notmuch_database_t *notmuch)
996 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
998 /* Many Xapian objects (and thus notmuch objects) hold references to
999 * the database, so merely deleting the database may not suffice to
1000 * close it. Thus, we explicitly close it here. */
1001 if (notmuch->xapian_db != NULL) {
1003 /* If there's an outstanding transaction, it's unclear if
1004 * closing the Xapian database commits everything up to
1005 * that transaction, or may discard committed (but
1006 * unflushed) transactions. To be certain, explicitly
1007 * cancel any outstanding transaction before closing. */
1008 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1009 notmuch->atomic_nesting)
1010 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1011 ->cancel_transaction ();
1013 /* Close the database. This implicitly flushes
1014 * outstanding changes. */
1015 notmuch->xapian_db->close();
1016 } catch (const Xapian::Error &error) {
1017 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1018 if (! notmuch->exception_reported) {
1019 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1020 error.get_msg().c_str());
1025 delete notmuch->term_gen;
1026 notmuch->term_gen = NULL;
1027 delete notmuch->query_parser;
1028 notmuch->query_parser = NULL;
1029 delete notmuch->xapian_db;
1030 notmuch->xapian_db = NULL;
1031 delete notmuch->value_range_processor;
1032 notmuch->value_range_processor = NULL;
1033 delete notmuch->date_range_processor;
1034 notmuch->date_range_processor = NULL;
1035 delete notmuch->last_mod_range_processor;
1036 notmuch->last_mod_range_processor = NULL;
1042 _notmuch_database_reopen (notmuch_database_t *notmuch)
1044 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1045 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1048 notmuch->xapian_db->reopen ();
1049 } catch (const Xapian::Error &error) {
1050 if (! notmuch->exception_reported) {
1051 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1052 error.get_msg ().c_str ());
1053 notmuch->exception_reported = true;
1055 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1060 return NOTMUCH_STATUS_SUCCESS;
1064 unlink_cb (const char *path,
1065 unused (const struct stat *sb),
1067 unused (struct FTW *ftw))
1069 return remove (path);
1073 rmtree (const char *path)
1075 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1078 class NotmuchCompactor : public Xapian::Compactor
1080 notmuch_compact_status_cb_t status_cb;
1081 void *status_closure;
1084 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1085 status_cb (cb), status_closure (closure) { }
1088 set_status (const std::string &table, const std::string &status)
1092 if (status_cb == NULL)
1095 if (status.length () == 0)
1096 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1098 msg = talloc_asprintf (NULL, " %s", status.c_str());
1104 status_cb (msg, status_closure);
1109 /* Compacts the given database, optionally saving the original database
1110 * in backup_path. Additionally, a callback function can be provided to
1111 * give the user feedback on the progress of the (likely long-lived)
1112 * compaction process.
1114 * The backup path must point to a directory on the same volume as the
1115 * original database. Passing a NULL backup_path will result in the
1116 * uncompacted database being deleted after compaction has finished.
1117 * Note that the database write lock will be held during the
1118 * compaction process to protect data integrity.
1121 notmuch_database_compact (const char *path,
1122 const char *backup_path,
1123 notmuch_compact_status_cb_t status_cb,
1127 char *notmuch_path, *xapian_path, *compact_xapian_path;
1128 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1129 notmuch_database_t *notmuch = NULL;
1130 struct stat statbuf;
1132 char *message = NULL;
1134 local = talloc_new (NULL);
1136 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1138 ret = notmuch_database_open_verbose (path,
1139 NOTMUCH_DATABASE_MODE_READ_WRITE,
1143 if (status_cb) status_cb (message, closure);
1147 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1148 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1152 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1153 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1157 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1158 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1162 if (backup_path == NULL) {
1163 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1164 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1167 keep_backup = false;
1173 if (stat (backup_path, &statbuf) != -1) {
1174 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1175 ret = NOTMUCH_STATUS_FILE_ERROR;
1178 if (errno != ENOENT) {
1179 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1181 ret = NOTMUCH_STATUS_FILE_ERROR;
1185 /* Unconditionally attempt to remove old work-in-progress database (if
1186 * any). This is "protected" by database lock. If this fails due to write
1187 * errors (etc), the following code will fail and provide error message.
1189 (void) rmtree (compact_xapian_path);
1192 NotmuchCompactor compactor (status_cb, closure);
1194 compactor.set_renumber (false);
1195 compactor.add_source (xapian_path);
1196 compactor.set_destdir (compact_xapian_path);
1197 compactor.compact ();
1198 } catch (const Xapian::Error &error) {
1199 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1200 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1204 if (rename (xapian_path, backup_path)) {
1205 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1206 xapian_path, backup_path, strerror (errno));
1207 ret = NOTMUCH_STATUS_FILE_ERROR;
1211 if (rename (compact_xapian_path, xapian_path)) {
1212 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1213 compact_xapian_path, xapian_path, strerror (errno));
1214 ret = NOTMUCH_STATUS_FILE_ERROR;
1218 if (! keep_backup) {
1219 if (rmtree (backup_path)) {
1220 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1221 backup_path, strerror (errno));
1222 ret = NOTMUCH_STATUS_FILE_ERROR;
1229 notmuch_status_t ret2;
1231 const char *str = notmuch_database_status_string (notmuch);
1232 if (status_cb && str)
1233 status_cb (str, closure);
1235 ret2 = notmuch_database_destroy (notmuch);
1237 /* don't clobber previous error status */
1238 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1242 talloc_free (local);
1248 notmuch_database_destroy (notmuch_database_t *notmuch)
1250 notmuch_status_t status;
1252 status = notmuch_database_close (notmuch);
1253 talloc_free (notmuch);
1259 notmuch_database_get_path (notmuch_database_t *notmuch)
1261 return notmuch->path;
1265 notmuch_database_get_version (notmuch_database_t *notmuch)
1267 unsigned int version;
1268 string version_string;
1272 version_string = notmuch->xapian_db->get_metadata ("version");
1273 if (version_string.empty ())
1276 str = version_string.c_str ();
1277 if (str == NULL || *str == '\0')
1280 version = strtoul (str, &end, 10);
1282 INTERNAL_ERROR ("Malformed database version: %s", str);
1288 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1290 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1291 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1292 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1295 static volatile sig_atomic_t do_progress_notify = 0;
1298 handle_sigalrm (unused (int signal))
1300 do_progress_notify = 1;
1303 /* Upgrade the current database.
1305 * After opening a database in read-write mode, the client should
1306 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1307 * if so, upgrade with this function before making any modifications.
1309 * The optional progress_notify callback can be used by the caller to
1310 * provide progress indication to the user. If non-NULL it will be
1311 * called periodically with 'count' as the number of messages upgraded
1312 * so far and 'total' the overall number of messages that will be
1316 notmuch_database_upgrade (notmuch_database_t *notmuch,
1317 void (*progress_notify) (void *closure,
1321 void *local = talloc_new (NULL);
1322 Xapian::TermIterator t, t_end;
1323 Xapian::WritableDatabase *db;
1324 struct sigaction action;
1325 struct itimerval timerval;
1326 bool timer_is_active = false;
1327 enum _notmuch_features target_features, new_features;
1328 notmuch_status_t status;
1329 notmuch_private_status_t private_status;
1330 notmuch_query_t *query = NULL;
1331 unsigned int count = 0, total = 0;
1333 status = _notmuch_database_ensure_writable (notmuch);
1337 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1339 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1340 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1342 if (! notmuch_database_needs_upgrade (notmuch))
1343 return NOTMUCH_STATUS_SUCCESS;
1345 if (progress_notify) {
1346 /* Set up our handler for SIGALRM */
1347 memset (&action, 0, sizeof (struct sigaction));
1348 action.sa_handler = handle_sigalrm;
1349 sigemptyset (&action.sa_mask);
1350 action.sa_flags = SA_RESTART;
1351 sigaction (SIGALRM, &action, NULL);
1353 /* Then start a timer to send SIGALRM once per second. */
1354 timerval.it_interval.tv_sec = 1;
1355 timerval.it_interval.tv_usec = 0;
1356 timerval.it_value.tv_sec = 1;
1357 timerval.it_value.tv_usec = 0;
1358 setitimer (ITIMER_REAL, &timerval, NULL);
1360 timer_is_active = true;
1363 /* Figure out how much total work we need to do. */
1365 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1366 NOTMUCH_FEATURE_LAST_MOD)) {
1367 query = notmuch_query_create (notmuch, "");
1370 status = notmuch_query_count_messages (query, &msg_count);
1375 notmuch_query_destroy (query);
1378 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1379 t_end = db->allterms_end ("XTIMESTAMP");
1380 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1383 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1384 /* The ghost message upgrade converts all thread_id_*
1385 * metadata values into ghost message documents. */
1386 t_end = db->metadata_keys_end ("thread_id_");
1387 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1391 /* Perform the upgrade in a transaction. */
1392 db->begin_transaction (true);
1394 /* Set the target features so we write out changes in the desired
1396 notmuch->features = target_features;
1398 /* Perform per-message upgrades. */
1400 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1401 NOTMUCH_FEATURE_LAST_MOD)) {
1402 notmuch_messages_t *messages;
1403 notmuch_message_t *message;
1406 query = notmuch_query_create (notmuch, "");
1408 status = notmuch_query_search_messages (query, &messages);
1412 notmuch_messages_valid (messages);
1413 notmuch_messages_move_to_next (messages))
1415 if (do_progress_notify) {
1416 progress_notify (closure, (double) count / total);
1417 do_progress_notify = 0;
1420 message = notmuch_messages_get (messages);
1422 /* Before version 1, each message document had its
1423 * filename in the data field. Copy that into the new
1424 * format by calling notmuch_message_add_filename.
1426 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1427 filename = _notmuch_message_talloc_copy_data (message);
1428 if (filename && *filename != '\0') {
1429 _notmuch_message_add_filename (message, filename);
1430 _notmuch_message_clear_data (message);
1432 talloc_free (filename);
1435 /* Prior to version 2, the "folder:" prefix was
1436 * probabilistic and stemmed. Change it to the current
1437 * boolean prefix. Add "path:" prefixes while at it.
1439 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1440 _notmuch_message_upgrade_folder (message);
1442 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1443 * track modification revisions. Give all messages the
1444 * next available revision; since we just started tracking
1445 * revisions for this database, that will be 1.
1447 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1448 _notmuch_message_upgrade_last_mod (message);
1450 _notmuch_message_sync (message);
1452 notmuch_message_destroy (message);
1457 notmuch_query_destroy (query);
1461 /* Perform per-directory upgrades. */
1463 /* Before version 1 we stored directory timestamps in
1464 * XTIMESTAMP documents instead of the current XDIRECTORY
1465 * documents. So copy those as well. */
1466 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1467 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1469 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1473 Xapian::PostingIterator p, p_end;
1474 std::string term = *t;
1476 p_end = notmuch->xapian_db->postlist_end (term);
1478 for (p = notmuch->xapian_db->postlist_begin (term);
1482 Xapian::Document document;
1484 notmuch_directory_t *directory;
1486 if (do_progress_notify) {
1487 progress_notify (closure, (double) count / total);
1488 do_progress_notify = 0;
1491 document = find_document_for_doc_id (notmuch, *p);
1492 mtime = Xapian::sortable_unserialise (
1493 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1495 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1496 NOTMUCH_FIND_CREATE, &status);
1497 notmuch_directory_set_mtime (directory, mtime);
1498 notmuch_directory_destroy (directory);
1500 db->delete_document (*p);
1507 /* Perform metadata upgrades. */
1509 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1510 * messages were stored as database metadata. Change these to
1513 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1514 notmuch_message_t *message;
1515 std::string message_id, thread_id;
1517 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1518 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1520 if (do_progress_notify) {
1521 progress_notify (closure, (double) count / total);
1522 do_progress_notify = 0;
1525 message_id = (*t).substr (
1526 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1527 thread_id = db->get_metadata (*t);
1529 /* Create ghost message */
1530 message = _notmuch_message_create_for_message_id (
1531 notmuch, message_id.c_str (), &private_status);
1532 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1533 /* Document already exists; ignore the stored thread ID */
1534 } else if (private_status ==
1535 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1536 private_status = _notmuch_message_initialize_ghost (
1537 message, thread_id.c_str ());
1538 if (! private_status)
1539 _notmuch_message_sync (message);
1542 if (private_status) {
1543 _notmuch_database_log (notmuch,
1544 "Upgrade failed while creating ghost messages.\n");
1545 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1549 /* Clear saved metadata thread ID */
1550 db->set_metadata (*t, "");
1556 status = NOTMUCH_STATUS_SUCCESS;
1557 db->set_metadata ("features", _print_features (local, notmuch->features));
1558 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1561 if (status == NOTMUCH_STATUS_SUCCESS)
1562 db->commit_transaction ();
1564 db->cancel_transaction ();
1566 if (timer_is_active) {
1567 /* Now stop the timer. */
1568 timerval.it_interval.tv_sec = 0;
1569 timerval.it_interval.tv_usec = 0;
1570 timerval.it_value.tv_sec = 0;
1571 timerval.it_value.tv_usec = 0;
1572 setitimer (ITIMER_REAL, &timerval, NULL);
1574 /* And disable the signal handler. */
1575 action.sa_handler = SIG_IGN;
1576 sigaction (SIGALRM, &action, NULL);
1580 notmuch_query_destroy (query);
1582 talloc_free (local);
1587 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1589 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1590 notmuch->atomic_nesting > 0)
1593 if (notmuch_database_needs_upgrade (notmuch))
1594 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1597 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1598 } catch (const Xapian::Error &error) {
1599 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1600 error.get_msg().c_str());
1601 notmuch->exception_reported = true;
1602 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1606 notmuch->atomic_nesting++;
1607 return NOTMUCH_STATUS_SUCCESS;
1611 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1613 Xapian::WritableDatabase *db;
1615 if (notmuch->atomic_nesting == 0)
1616 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1618 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1619 notmuch->atomic_nesting > 1)
1622 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1624 db->commit_transaction ();
1626 /* This is a hack for testing. Xapian never flushes on a
1627 * non-flushed commit, even if the flush threshold is 1.
1628 * However, we rely on flushing to test atomicity. */
1629 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1630 if (thresh && atoi (thresh) == 1)
1632 } catch (const Xapian::Error &error) {
1633 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1634 error.get_msg().c_str());
1635 notmuch->exception_reported = true;
1636 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1639 if (notmuch->atomic_dirty) {
1640 ++notmuch->revision;
1641 notmuch->atomic_dirty = false;
1645 notmuch->atomic_nesting--;
1646 return NOTMUCH_STATUS_SUCCESS;
1650 notmuch_database_get_revision (notmuch_database_t *notmuch,
1654 *uuid = notmuch->uuid;
1655 return notmuch->revision;
1658 /* We allow the user to use arbitrarily long paths for directories. But
1659 * we have a term-length limit. So if we exceed that, we'll use the
1660 * SHA-1 of the path for the database term.
1662 * Note: This function may return the original value of 'path'. If it
1663 * does not, then the caller is responsible to free() the returned
1667 _notmuch_database_get_directory_db_path (const char *path)
1669 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1671 if (term_len > NOTMUCH_TERM_MAX)
1672 return _notmuch_sha1_of_string (path);
1677 /* Given a path, split it into two parts: the directory part is all
1678 * components except for the last, and the basename is that last
1679 * component. Getting the return-value for either part is optional
1680 * (the caller can pass NULL).
1682 * The original 'path' can represent either a regular file or a
1683 * directory---the splitting will be carried out in the same way in
1684 * either case. Trailing slashes on 'path' will be ignored, and any
1685 * cases of multiple '/' characters appearing in series will be
1686 * treated as a single '/'.
1688 * Allocation (if any) will have 'ctx' as the talloc owner. But
1689 * pointers will be returned within the original path string whenever
1692 * Note: If 'path' is non-empty and contains no non-trailing slash,
1693 * (that is, consists of a filename with no parent directory), then
1694 * the directory returned will be an empty string. However, if 'path'
1695 * is an empty string, then both directory and basename will be
1699 _notmuch_database_split_path (void *ctx,
1701 const char **directory,
1702 const char **basename)
1706 if (path == NULL || *path == '\0') {
1711 return NOTMUCH_STATUS_SUCCESS;
1714 /* Find the last slash (not counting a trailing slash), if any. */
1716 slash = path + strlen (path) - 1;
1718 /* First, skip trailing slashes. */
1719 while (slash != path && *slash == '/')
1722 /* Then, find a slash. */
1723 while (slash != path && *slash != '/') {
1730 /* Finally, skip multiple slashes. */
1731 while (slash != path && *(slash - 1) == '/')
1734 if (slash == path) {
1736 *directory = talloc_strdup (ctx, "");
1741 *directory = talloc_strndup (ctx, path, slash - path);
1744 return NOTMUCH_STATUS_SUCCESS;
1747 /* Find the document ID of the specified directory.
1749 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1750 * created if one does not exist for 'path'. Otherwise, if the
1751 * directory document does not exist, this sets *directory_id to
1752 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1755 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1757 notmuch_find_flags_t flags,
1758 unsigned int *directory_id)
1760 notmuch_directory_t *directory;
1761 notmuch_status_t status;
1765 return NOTMUCH_STATUS_SUCCESS;
1768 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1769 if (status || !directory) {
1774 *directory_id = _notmuch_directory_get_document_id (directory);
1776 notmuch_directory_destroy (directory);
1778 return NOTMUCH_STATUS_SUCCESS;
1782 _notmuch_database_get_directory_path (void *ctx,
1783 notmuch_database_t *notmuch,
1784 unsigned int doc_id)
1786 Xapian::Document document;
1788 document = find_document_for_doc_id (notmuch, doc_id);
1790 return talloc_strdup (ctx, document.get_data ().c_str ());
1793 /* Given a legal 'filename' for the database, (either relative to
1794 * database path or absolute with initial components identical to
1795 * database path), return a new string (with 'ctx' as the talloc
1796 * owner) suitable for use as a direntry term value.
1798 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1799 * will be created in the database as needed. Otherwise, if the
1800 * necessary directory documents do not exist, this sets
1801 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1804 _notmuch_database_filename_to_direntry (void *ctx,
1805 notmuch_database_t *notmuch,
1806 const char *filename,
1807 notmuch_find_flags_t flags,
1810 const char *relative, *directory, *basename;
1811 Xapian::docid directory_id;
1812 notmuch_status_t status;
1814 relative = _notmuch_database_relative_path (notmuch, filename);
1816 status = _notmuch_database_split_path (ctx, relative,
1817 &directory, &basename);
1821 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1823 if (status || directory_id == (unsigned int)-1) {
1828 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1830 return NOTMUCH_STATUS_SUCCESS;
1833 /* Given a legal 'path' for the database, return the relative path.
1835 * The return value will be a pointer to the original path contents,
1836 * and will be either the original string (if 'path' was relative) or
1837 * a portion of the string (if path was absolute and begins with the
1841 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1844 const char *db_path, *relative;
1845 unsigned int db_path_len;
1847 db_path = notmuch_database_get_path (notmuch);
1848 db_path_len = strlen (db_path);
1852 if (*relative == '/') {
1853 while (*relative == '/' && *(relative+1) == '/')
1856 if (strncmp (relative, db_path, db_path_len) == 0)
1858 relative += db_path_len;
1859 while (*relative == '/')
1868 notmuch_database_get_directory (notmuch_database_t *notmuch,
1870 notmuch_directory_t **directory)
1872 notmuch_status_t status;
1874 if (directory == NULL)
1875 return NOTMUCH_STATUS_NULL_POINTER;
1879 *directory = _notmuch_directory_create (notmuch, path,
1880 NOTMUCH_FIND_LOOKUP, &status);
1881 } catch (const Xapian::Error &error) {
1882 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1883 error.get_msg().c_str());
1884 notmuch->exception_reported = true;
1885 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1890 /* Allocate a document ID that satisfies the following criteria:
1892 * 1. The ID does not exist for any document in the Xapian database
1894 * 2. The ID was not previously returned from this function
1896 * 3. The ID is the smallest integer satisfying (1) and (2)
1898 * This function will trigger an internal error if these constraints
1899 * cannot all be satisfied, (that is, the pool of available document
1900 * IDs has been exhausted).
1903 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1905 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1907 notmuch->last_doc_id++;
1909 if (notmuch->last_doc_id == 0)
1910 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1912 return notmuch->last_doc_id;
1916 notmuch_database_remove_message (notmuch_database_t *notmuch,
1917 const char *filename)
1919 notmuch_status_t status;
1920 notmuch_message_t *message;
1922 status = notmuch_database_find_message_by_filename (notmuch, filename,
1925 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1926 status = _notmuch_message_remove_filename (message, filename);
1927 if (status == NOTMUCH_STATUS_SUCCESS)
1928 _notmuch_message_delete (message);
1929 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1930 _notmuch_message_sync (message);
1932 notmuch_message_destroy (message);
1939 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1940 const char *filename,
1941 notmuch_message_t **message_ret)
1944 const char *prefix = _find_prefix ("file-direntry");
1945 char *direntry, *term;
1946 Xapian::PostingIterator i, end;
1947 notmuch_status_t status;
1949 if (message_ret == NULL)
1950 return NOTMUCH_STATUS_NULL_POINTER;
1952 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1953 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1955 /* return NULL on any failure */
1956 *message_ret = NULL;
1958 local = talloc_new (notmuch);
1961 status = _notmuch_database_filename_to_direntry (
1962 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1963 if (status || !direntry)
1966 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1968 find_doc_ids_for_term (notmuch, term, &i, &end);
1971 notmuch_private_status_t private_status;
1973 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1975 if (*message_ret == NULL)
1976 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1978 } catch (const Xapian::Error &error) {
1979 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1980 error.get_msg().c_str());
1981 notmuch->exception_reported = true;
1982 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1986 talloc_free (local);
1988 if (status && *message_ret) {
1989 notmuch_message_destroy (*message_ret);
1990 *message_ret = NULL;
1995 notmuch_string_list_t *
1996 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1997 Xapian::TermIterator &end,
2000 int prefix_len = strlen (prefix);
2001 notmuch_string_list_t *list;
2003 list = _notmuch_string_list_create (ctx);
2004 if (unlikely (list == NULL))
2007 for (i.skip_to (prefix); i != end; i++) {
2008 /* Terminate loop at first term without desired prefix. */
2009 if (strncmp ((*i).c_str (), prefix, prefix_len))
2012 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2019 notmuch_database_get_all_tags (notmuch_database_t *db)
2021 Xapian::TermIterator i, end;
2022 notmuch_string_list_t *tags;
2025 i = db->xapian_db->allterms_begin();
2026 end = db->xapian_db->allterms_end();
2027 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2028 _find_prefix ("tag"));
2029 _notmuch_string_list_sort (tags);
2030 return _notmuch_tags_create (db, tags);
2031 } catch (const Xapian::Error &error) {
2032 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2033 error.get_msg().c_str());
2034 db->exception_reported = true;
2040 notmuch_database_status_string (const notmuch_database_t *notmuch)
2042 return notmuch->status_string;