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 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
64 _log_xapian_exception (const char *where, notmuch_database_t *notmuch, const Xapian::Error error) {
65 _notmuch_database_log (notmuch,
66 "A Xapian exception occurred at %s: %s\n",
68 error.get_msg ().c_str ());
69 notmuch->exception_reported = true;
72 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
74 * We currently have three different types of documents (mail, ghost,
75 * and directory) and also some metadata.
77 * There are two kinds of prefixes used in notmuch. There are the
78 * human friendly 'prefix names' like "thread:", which are also used
79 * in the query parser, and the actual prefix terms in the database
80 * (e.g. "G"). The correspondence is maintained in the file scope data
81 * structure 'prefix_table'.
85 * A mail document is associated with a particular email message. It
86 * is stored in one or more files on disk and is uniquely identified
87 * by its "id" field (which is generally the message ID). It is
88 * indexed with the following prefixed terms which the database uses
89 * to construct threads, etc.:
91 * Single terms of given prefix:
95 * id: Unique ID of mail. This is from the Message-ID header
96 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
97 * If it's present and too long, then we use
98 * "notmuch-sha1-<sha1_sum_of_message_id>".
99 * If this header is not present, we use
100 * "notmuch-sha1-<sha1_sum_of_entire_file>".
102 * thread: The ID of the thread to which the mail belongs
104 * replyto: The ID from the In-Reply-To header of the mail (if any).
106 * Multiple terms of given prefix:
108 * reference: All message IDs from In-Reply-To and References
109 * headers in the message.
111 * tag: Any tags associated with this message by the user.
113 * file-direntry: A colon-separated pair of values
114 * (INTEGER:STRING), where INTEGER is the
115 * document ID of a directory document, and
116 * STRING is the name of a file within that
117 * directory for this mail message.
119 * property: Has a property with key=value
120 * FIXME: if no = is present, should match on any value
122 * A mail document also has four values:
124 * TIMESTAMP: The time_t value corresponding to the message's
127 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
129 * FROM: The value of the "From" header
131 * SUBJECT: The value of the "Subject" header
133 * LAST_MOD: The revision number as of the last tag or
136 * The prefixed terms described above are also searchable without an
137 * explicit field name, but as of notmuch 0.29 this is due to
138 * query-parser setup, not extra terms in the database. In addition,
139 * terms from the content of the message are added without a prefix
140 * for use by the user in searching. Note that the prefix name "body"
141 * is used to refer to the empty prefix string in the database.
143 * The path of the containing folder is added with the "folder" prefix
144 * (see _notmuch_message_add_folder_terms). Sub-paths of the the path
145 * of the mail message are added with the "path" prefix.
147 * The data portion of a mail document is empty.
149 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
150 * -----------------------------------------------
151 * A ghost mail document is like a mail document, but where we don't
152 * have the message content. These are used to track thread reference
153 * information for messages we haven't received.
155 * A ghost mail document has type: ghost; id and thread fields that
156 * are identical to the mail document fields; and a MESSAGE_ID value.
160 * A directory document is used by a client of the notmuch library to
161 * maintain data necessary to allow for efficient polling of mail
164 * All directory documents contain one term:
166 * directory: The directory path (relative to the database path)
167 * Or the SHA1 sum of the directory path (if the
168 * path itself is too long to fit in a Xapian
171 * And all directory documents for directories other than top-level
172 * directories also contain the following term:
174 * directory-direntry: A colon-separated pair of values
175 * (INTEGER:STRING), where INTEGER is the
176 * document ID of the parent directory
177 * document, and STRING is the name of this
178 * directory within that parent.
180 * All directory documents have a single value:
182 * TIMESTAMP: The mtime of the directory (at last scan)
184 * The data portion of a directory document contains the path of the
185 * directory (relative to the database path).
189 * Xapian allows us to store arbitrary name-value pairs as
190 * "metadata". We currently use the following metadata names with the
193 * version The database schema version, (which is distinct
194 * from both the notmuch package version (see
195 * notmuch --version) and the libnotmuch library
196 * version. The version is stored as an base-10
197 * ASCII integer. The initial database version
198 * was 1, (though a schema existed before that
199 * were no "version" database value existed at
200 * all). Successive versions are allocated as
201 * changes are made to the database (such as by
202 * indexing new fields).
204 * features The set of features supported by this
205 * database. This consists of a set of
206 * '\n'-separated lines, where each is a feature
207 * name, a '\t', and compatibility flags. If the
208 * compatibility flags contain 'w', then the
209 * opener must support this feature to safely
210 * write this database. If the compatibility
211 * flags contain 'r', then the opener must
212 * support this feature to read this database.
213 * Introduced in database version 3.
215 * last_thread_id The last thread ID generated. This is stored
216 * as a 16-byte hexadecimal ASCII representation
217 * of a 64-bit unsigned integer. The first ID
218 * generated is 1 and the value will be
219 * incremented for each thread ID.
221 * C* metadata keys starting with C indicate
222 * configuration data. It can be managed with the
223 * n_database_*config* API. There is a convention
224 * of hierarchical keys separated by '.' (e.g.
225 * query.notmuch stores the value for the named
226 * query 'notmuch'), but it is not enforced by the
232 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
233 * Instead, the database has the following additional database
236 * thread_id_* A pre-allocated thread ID for a particular
237 * message. This is actually an arbitrarily large
238 * family of metadata name. Any particular name is
239 * formed by concatenating "thread_id_" with a message
240 * ID (or the SHA1 sum of a message ID if it is very
241 * long---see description of 'id' in the mail
242 * document). The value stored is a thread ID.
244 * These thread ID metadata values are stored
245 * whenever a message references a parent message
246 * that does not yet exist in the database. A
247 * thread ID will be allocated and stored, and if
248 * the message is later added, the stored thread
249 * ID will be used (and the metadata value will
252 * Even before a message is added, it's
253 * pre-allocated thread ID is useful so that all
254 * descendant messages that reference this common
255 * parent can be recognized as belonging to the
259 /* With these prefix values we follow the conventions published here:
261 * https://xapian.org/docs/omega/termprefixes.html
263 * as much as makes sense. Note that I took some liberty in matching
264 * the reserved prefix values to notmuch concepts, (for example, 'G'
265 * is documented as "newsGroup (or similar entity - e.g. a web forum
266 * name)", for which I think the thread is the closest analogue in
267 * notmuch. This in spite of the fact that we will eventually be
268 * storing mailing-list messages where 'G' for "mailing list name"
269 * might be even a closer analogue. I'm treating the single-character
270 * prefixes preferentially for core notmuch concepts (which will be
271 * nearly universal to all mail messages).
275 prefix_t prefix_table[] = {
276 /* name term prefix flags */
277 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
278 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
279 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
280 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
281 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
282 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
283 { "body", "", NOTMUCH_FIELD_EXTERNAL |
284 NOTMUCH_FIELD_PROBABILISTIC },
285 { "thread", "G", NOTMUCH_FIELD_EXTERNAL |
286 NOTMUCH_FIELD_PROCESSOR },
287 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
288 NOTMUCH_FIELD_PROCESSOR },
289 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
290 NOTMUCH_FIELD_PROCESSOR },
291 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
292 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
293 NOTMUCH_FIELD_PROCESSOR },
294 { "path", "P", NOTMUCH_FIELD_EXTERNAL |
295 NOTMUCH_FIELD_PROCESSOR },
296 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
298 * Unconditionally add ':' to reduce potential ambiguity with
299 * overlapping prefixes and/or terms that start with capital
300 * letters. See Xapian document termprefixes.html for related
303 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
304 NOTMUCH_FIELD_PROCESSOR },
305 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
306 NOTMUCH_FIELD_PROCESSOR },
307 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
308 NOTMUCH_FIELD_PROCESSOR },
309 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
310 NOTMUCH_FIELD_PROBABILISTIC |
311 NOTMUCH_FIELD_PROCESSOR },
312 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
313 NOTMUCH_FIELD_PROBABILISTIC },
314 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
315 NOTMUCH_FIELD_PROBABILISTIC },
316 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
317 NOTMUCH_FIELD_PROBABILISTIC },
318 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
319 NOTMUCH_FIELD_PROBABILISTIC |
320 NOTMUCH_FIELD_PROCESSOR },
324 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
327 notmuch->query_parser->add_prefix ("", prefix->prefix);
328 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
329 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
331 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
334 notmuch_string_map_iterator_t *
335 _notmuch_database_user_headers (notmuch_database_t *notmuch)
337 return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
341 _user_prefix (void *ctx, const char *name)
343 return talloc_asprintf (ctx, "XU%s:", name);
346 static notmuch_status_t
347 _setup_user_query_fields (notmuch_database_t *notmuch)
349 notmuch_config_list_t *list;
350 notmuch_status_t status;
352 notmuch->user_prefix = _notmuch_string_map_create (notmuch);
353 if (notmuch->user_prefix == NULL)
354 return NOTMUCH_STATUS_OUT_OF_MEMORY;
356 notmuch->user_header = _notmuch_string_map_create (notmuch);
357 if (notmuch->user_header == NULL)
358 return NOTMUCH_STATUS_OUT_OF_MEMORY;
360 status = notmuch_database_get_config_list (notmuch, CONFIG_HEADER_PREFIX, &list);
364 for (; notmuch_config_list_valid (list); notmuch_config_list_move_to_next (list)) {
366 prefix_t query_field;
368 const char *key = notmuch_config_list_key (list)
369 + sizeof (CONFIG_HEADER_PREFIX) - 1;
371 _notmuch_string_map_append (notmuch->user_prefix,
373 _user_prefix (notmuch, key));
375 _notmuch_string_map_append (notmuch->user_header,
377 notmuch_config_list_value (list));
379 query_field.name = talloc_strdup (notmuch, key);
380 query_field.prefix = _user_prefix (notmuch, key);
381 query_field.flags = NOTMUCH_FIELD_PROBABILISTIC
382 | NOTMUCH_FIELD_EXTERNAL;
384 _setup_query_field_default (&query_field, notmuch);
387 notmuch_config_list_destroy (list);
389 return NOTMUCH_STATUS_SUCCESS;
393 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
395 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
396 Xapian::FieldProcessor *fp;
398 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
399 fp = (new DateFieldProcessor(NOTMUCH_VALUE_TIMESTAMP))->release ();
400 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
401 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
402 else if (STRNCMP_LITERAL (prefix->name, "thread") == 0)
403 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
405 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
406 *notmuch->query_parser, notmuch))->release ();
408 /* we treat all field-processor fields as boolean in order to get the raw input */
410 notmuch->query_parser->add_prefix ("", prefix->prefix);
411 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
413 _setup_query_field_default (prefix, notmuch);
418 _find_prefix (const char *name)
422 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
423 if (strcmp (name, prefix_table[i].name) == 0)
424 return prefix_table[i].prefix;
427 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
432 /* Like find prefix, but include the possibility of user defined
433 * prefixes specific to this database */
436 _notmuch_database_prefix (notmuch_database_t *notmuch, const char *name)
440 /*XXX TODO: reduce code duplication */
441 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
442 if (strcmp (name, prefix_table[i].name) == 0)
443 return prefix_table[i].prefix;
446 if (notmuch->user_prefix)
447 return _notmuch_string_map_get (notmuch->user_prefix, name);
452 static const struct {
453 /* NOTMUCH_FEATURE_* value. */
454 _notmuch_features value;
455 /* Feature name as it appears in the database. This name should
456 * be appropriate for displaying to the user if an older version
457 * of notmuch doesn't support this feature. */
459 /* Compatibility flags when this feature is declared. */
461 } feature_names[] = {
462 { NOTMUCH_FEATURE_FILE_TERMS,
463 "multiple paths per message", "rw" },
464 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
465 "relative directory paths", "rw" },
466 /* Header values are not required for reading a database because a
467 * reader can just refer to the message file. */
468 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
469 "from/subject/message-ID in database", "w" },
470 { NOTMUCH_FEATURE_BOOL_FOLDER,
471 "exact folder:/path: search", "rw" },
472 { NOTMUCH_FEATURE_GHOSTS,
473 "mail documents for missing messages", "w" },
474 /* Knowledge of the index mime-types are not required for reading
475 * a database because a reader will just be unable to query
477 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
478 "indexed MIME types", "w" },
479 { NOTMUCH_FEATURE_LAST_MOD,
480 "modification tracking", "w" },
481 /* Existing databases will work fine for all queries not involving
483 { NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY,
484 "index body and headers separately", "w" },
488 notmuch_status_to_string (notmuch_status_t status)
491 case NOTMUCH_STATUS_SUCCESS:
492 return "No error occurred";
493 case NOTMUCH_STATUS_OUT_OF_MEMORY:
494 return "Out of memory";
495 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
496 return "Attempt to write to a read-only database";
497 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
498 return "A Xapian exception occurred";
499 case NOTMUCH_STATUS_FILE_ERROR:
500 return "Something went wrong trying to read or write a file";
501 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
502 return "File is not an email";
503 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
504 return "Message ID is identical to a message in database";
505 case NOTMUCH_STATUS_NULL_POINTER:
506 return "Erroneous NULL pointer";
507 case NOTMUCH_STATUS_TAG_TOO_LONG:
508 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
509 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
510 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
511 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
512 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
513 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
514 return "Unsupported operation";
515 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
516 return "Operation requires a database upgrade";
517 case NOTMUCH_STATUS_PATH_ERROR:
518 return "Path supplied is illegal for this function";
519 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
520 return "Crypto protocol missing, malformed, or unintelligible";
521 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
522 return "Crypto engine initialization failure";
523 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
524 return "Unknown crypto protocol";
526 case NOTMUCH_STATUS_LAST_STATUS:
527 return "Unknown error status value";
532 _notmuch_database_log (notmuch_database_t *notmuch,
538 va_start (va_args, format);
540 if (notmuch->status_string)
541 talloc_free (notmuch->status_string);
543 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
548 _notmuch_database_log_append (notmuch_database_t *notmuch,
554 va_start (va_args, format);
556 if (notmuch->status_string)
557 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
559 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
565 find_doc_ids_for_term (notmuch_database_t *notmuch,
567 Xapian::PostingIterator *begin,
568 Xapian::PostingIterator *end)
570 *begin = notmuch->xapian_db->postlist_begin (term);
572 *end = notmuch->xapian_db->postlist_end (term);
576 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
577 const char *prefix_name,
579 Xapian::PostingIterator *begin,
580 Xapian::PostingIterator *end)
584 term = talloc_asprintf (notmuch, "%s%s",
585 _find_prefix (prefix_name), value);
587 find_doc_ids_for_term (notmuch, term, begin, end);
592 notmuch_private_status_t
593 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
594 const char *prefix_name,
596 unsigned int *doc_id)
598 Xapian::PostingIterator i, end;
600 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
604 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
609 #if DEBUG_DATABASE_SANITY
613 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
617 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
620 static Xapian::Document
621 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
623 return notmuch->xapian_db->get_document (doc_id);
626 /* Generate a compressed version of 'message_id' of the form:
628 * notmuch-sha1-<sha1_sum_of_message_id>
631 _notmuch_message_id_compressed (void *ctx, const char *message_id)
633 char *sha1, *compressed;
635 sha1 = _notmuch_sha1_of_string (message_id);
637 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
644 notmuch_database_find_message (notmuch_database_t *notmuch,
645 const char *message_id,
646 notmuch_message_t **message_ret)
648 notmuch_private_status_t status;
651 if (message_ret == NULL)
652 return NOTMUCH_STATUS_NULL_POINTER;
654 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
655 message_id = _notmuch_message_id_compressed (notmuch, message_id);
658 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
659 message_id, &doc_id);
661 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
664 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
666 if (*message_ret == NULL)
667 return NOTMUCH_STATUS_OUT_OF_MEMORY;
670 return NOTMUCH_STATUS_SUCCESS;
671 } catch (const Xapian::Error &error) {
672 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
673 error.get_msg ().c_str ());
674 notmuch->exception_reported = true;
676 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
681 notmuch_database_create (const char *path, notmuch_database_t **database)
683 char *status_string = NULL;
684 notmuch_status_t status;
686 status = notmuch_database_create_verbose (path, database,
690 fputs (status_string, stderr);
691 free (status_string);
698 notmuch_database_create_verbose (const char *path,
699 notmuch_database_t **database,
700 char **status_string)
702 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
703 notmuch_database_t *notmuch = NULL;
704 char *notmuch_path = NULL;
705 char *message = NULL;
710 message = strdup ("Error: Cannot create a database for a NULL path.\n");
711 status = NOTMUCH_STATUS_NULL_POINTER;
715 if (path[0] != '/') {
716 message = strdup ("Error: Database path must be absolute.\n");
717 status = NOTMUCH_STATUS_PATH_ERROR;
721 err = stat (path, &st);
723 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
724 path, strerror (errno)));
725 status = NOTMUCH_STATUS_FILE_ERROR;
729 if (! S_ISDIR (st.st_mode)) {
730 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
731 "Not a directory.\n",
733 status = NOTMUCH_STATUS_FILE_ERROR;
737 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
739 err = mkdir (notmuch_path, 0755);
742 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
743 notmuch_path, strerror (errno)));
744 status = NOTMUCH_STATUS_FILE_ERROR;
748 status = notmuch_database_open_verbose (path,
749 NOTMUCH_DATABASE_MODE_READ_WRITE,
754 /* Upgrade doesn't add these feature to existing databases, but
755 * new databases have them. */
756 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
757 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
758 notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
760 status = notmuch_database_upgrade (notmuch, NULL, NULL);
762 notmuch_database_close (notmuch);
768 talloc_free (notmuch_path);
772 *status_string = message;
779 talloc_free (notmuch);
784 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
786 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
787 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
788 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
791 return NOTMUCH_STATUS_SUCCESS;
794 /* Allocate a revision number for the next change. */
796 _notmuch_database_new_revision (notmuch_database_t *notmuch)
798 unsigned long new_revision = notmuch->revision + 1;
800 /* If we're in an atomic section, hold off on updating the
801 * committed revision number until we commit the atomic section.
803 if (notmuch->atomic_nesting)
804 notmuch->atomic_dirty = true;
806 notmuch->revision = new_revision;
811 /* Parse a database features string from the given database version.
812 * Returns the feature bit set.
814 * For version < 3, this ignores the features string and returns a
815 * hard-coded set of features.
817 * If there are unrecognized features that are required to open the
818 * database in mode (which should be 'r' or 'w'), return a
819 * comma-separated list of unrecognized but required features in
820 * *incompat_out suitable for presenting to the user. *incompat_out
821 * will be allocated from ctx.
823 static _notmuch_features
824 _parse_features (const void *ctx, const char *features, unsigned int version,
825 char mode, char **incompat_out)
827 _notmuch_features res = static_cast<_notmuch_features>(0);
828 unsigned int namelen, i;
832 /* Prior to database version 3, features were implied by the
835 return NOTMUCH_FEATURES_V0;
836 else if (version == 1)
837 return NOTMUCH_FEATURES_V1;
838 else if (version == 2)
839 return NOTMUCH_FEATURES_V2;
841 /* Parse the features string */
842 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
843 flags = strchr (features, '\t');
844 if (! flags || flags > features + llen)
846 namelen = flags - features;
848 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
849 if (strlen (feature_names[i].name) == namelen &&
850 strncmp (feature_names[i].name, features, namelen) == 0) {
851 res |= feature_names[i].value;
856 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
857 /* Unrecognized feature */
858 const char *have = strchr (flags, mode);
859 if (have && have < features + llen) {
860 /* This feature is required to access this database in
861 * 'mode', but we don't understand it. */
863 *incompat_out = talloc_strdup (ctx, "");
864 *incompat_out = talloc_asprintf_append_buffer (
865 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
875 _print_features (const void *ctx, unsigned int features)
878 char *res = talloc_strdup (ctx, "");
880 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
881 if (features & feature_names[i].value)
882 res = talloc_asprintf_append_buffer (
883 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
889 notmuch_database_open (const char *path,
890 notmuch_database_mode_t mode,
891 notmuch_database_t **database)
893 char *status_string = NULL;
894 notmuch_status_t status;
896 status = notmuch_database_open_verbose (path, mode, database,
900 fputs (status_string, stderr);
901 free (status_string);
908 notmuch_database_open_verbose (const char *path,
909 notmuch_database_mode_t mode,
910 notmuch_database_t **database,
911 char **status_string)
913 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
914 void *local = talloc_new (NULL);
915 notmuch_database_t *notmuch = NULL;
916 char *notmuch_path, *xapian_path, *incompat_features;
917 char *message = NULL;
920 unsigned int i, version;
921 static int initialized = 0;
924 message = strdup ("Error: Cannot open a database for a NULL path.\n");
925 status = NOTMUCH_STATUS_NULL_POINTER;
929 if (path[0] != '/') {
930 message = strdup ("Error: Database path must be absolute.\n");
931 status = NOTMUCH_STATUS_PATH_ERROR;
935 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
936 message = strdup ("Out of memory\n");
937 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
941 err = stat (notmuch_path, &st);
943 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
944 notmuch_path, strerror (errno)));
945 status = NOTMUCH_STATUS_FILE_ERROR;
949 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
950 message = strdup ("Out of memory\n");
951 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
955 /* Initialize the GLib type system and threads */
956 #if ! GLIB_CHECK_VERSION (2, 35, 1)
960 /* Initialize gmime */
966 notmuch = talloc_zero (NULL, notmuch_database_t);
967 notmuch->exception_reported = false;
968 notmuch->status_string = NULL;
969 notmuch->path = talloc_strdup (notmuch, path);
971 strip_trailing (notmuch->path, '/');
973 notmuch->mode = mode;
974 notmuch->atomic_nesting = 0;
977 string last_thread_id;
980 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
981 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
984 notmuch->xapian_db = new Xapian::Database (xapian_path);
987 /* Check version. As of database version 3, we represent
988 * changes in terms of features, so assume a version bump
989 * means a dramatically incompatible change. */
990 version = notmuch_database_get_version (notmuch);
991 if (version > NOTMUCH_DATABASE_VERSION) {
992 IGNORE_RESULT (asprintf (&message,
993 "Error: Notmuch database at %s\n"
994 " has a newer database format version (%u) than supported by this\n"
995 " version of notmuch (%u).\n",
996 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
997 notmuch_database_destroy (notmuch);
999 status = NOTMUCH_STATUS_FILE_ERROR;
1003 /* Check features. */
1004 incompat_features = NULL;
1005 notmuch->features = _parse_features (
1006 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1007 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1008 &incompat_features);
1009 if (incompat_features) {
1010 IGNORE_RESULT (asprintf (&message,
1011 "Error: Notmuch database at %s\n"
1012 " requires features (%s)\n"
1013 " not supported by this version of notmuch.\n",
1014 notmuch_path, incompat_features));
1015 notmuch_database_destroy (notmuch);
1017 status = NOTMUCH_STATUS_FILE_ERROR;
1021 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1022 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1023 if (last_thread_id.empty ()) {
1024 notmuch->last_thread_id = 0;
1029 str = last_thread_id.c_str ();
1030 notmuch->last_thread_id = strtoull (str, &end, 16);
1032 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1035 /* Get current highest revision number. */
1036 last_mod = notmuch->xapian_db->get_value_upper_bound (
1037 NOTMUCH_VALUE_LAST_MOD);
1038 if (last_mod.empty ())
1039 notmuch->revision = 0;
1041 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1042 notmuch->uuid = talloc_strdup (
1043 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1045 notmuch->query_parser = new Xapian::QueryParser;
1046 notmuch->term_gen = new Xapian::TermGenerator;
1047 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1048 notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1049 notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP, "date:");
1050 notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1051 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1052 notmuch->query_parser->set_database (*notmuch->xapian_db);
1053 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1054 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1055 notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
1056 notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
1057 notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
1059 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1060 const prefix_t *prefix = &prefix_table[i];
1061 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1062 _setup_query_field (prefix, notmuch);
1065 status = _setup_user_query_fields (notmuch);
1066 } catch (const Xapian::Error &error) {
1067 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1068 error.get_msg ().c_str ()));
1069 notmuch_database_destroy (notmuch);
1071 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1075 talloc_free (local);
1079 *status_string = message;
1085 *database = notmuch;
1087 talloc_free (notmuch);
1090 notmuch->open = true;
1096 notmuch_database_close (notmuch_database_t *notmuch)
1098 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1100 /* Many Xapian objects (and thus notmuch objects) hold references to
1101 * the database, so merely deleting the database may not suffice to
1102 * close it. Thus, we explicitly close it here. */
1103 if (notmuch->open) {
1105 /* If there's an outstanding transaction, it's unclear if
1106 * closing the Xapian database commits everything up to
1107 * that transaction, or may discard committed (but
1108 * unflushed) transactions. To be certain, explicitly
1109 * cancel any outstanding transaction before closing. */
1110 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1111 notmuch->atomic_nesting)
1112 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1113 ->cancel_transaction ();
1115 /* Close the database. This implicitly flushes
1116 * outstanding changes. */
1117 notmuch->xapian_db->close ();
1118 } catch (const Xapian::Error &error) {
1119 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1120 if (! notmuch->exception_reported) {
1121 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1122 error.get_msg ().c_str ());
1126 notmuch->open = false;
1131 _notmuch_database_reopen (notmuch_database_t *notmuch)
1133 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1134 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1137 notmuch->xapian_db->reopen ();
1138 } catch (const Xapian::Error &error) {
1139 if (! notmuch->exception_reported) {
1140 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1141 error.get_msg ().c_str ());
1142 notmuch->exception_reported = true;
1144 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1149 return NOTMUCH_STATUS_SUCCESS;
1153 unlink_cb (const char *path,
1154 unused (const struct stat *sb),
1156 unused (struct FTW *ftw))
1158 return remove (path);
1162 rmtree (const char *path)
1164 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1167 class NotmuchCompactor : public Xapian::Compactor
1169 notmuch_compact_status_cb_t status_cb;
1170 void *status_closure;
1173 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1174 status_cb (cb), status_closure (closure)
1179 set_status (const std::string &table, const std::string &status)
1183 if (status_cb == NULL)
1186 if (status.length () == 0)
1187 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
1189 msg = talloc_asprintf (NULL, " %s", status.c_str ());
1195 status_cb (msg, status_closure);
1200 /* Compacts the given database, optionally saving the original database
1201 * in backup_path. Additionally, a callback function can be provided to
1202 * give the user feedback on the progress of the (likely long-lived)
1203 * compaction process.
1205 * The backup path must point to a directory on the same volume as the
1206 * original database. Passing a NULL backup_path will result in the
1207 * uncompacted database being deleted after compaction has finished.
1208 * Note that the database write lock will be held during the
1209 * compaction process to protect data integrity.
1212 notmuch_database_compact (const char *path,
1213 const char *backup_path,
1214 notmuch_compact_status_cb_t status_cb,
1218 char *notmuch_path, *xapian_path, *compact_xapian_path;
1219 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1220 notmuch_database_t *notmuch = NULL;
1221 struct stat statbuf;
1223 char *message = NULL;
1225 local = talloc_new (NULL);
1227 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1229 ret = notmuch_database_open_verbose (path,
1230 NOTMUCH_DATABASE_MODE_READ_WRITE,
1234 if (status_cb) status_cb (message, closure);
1238 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1239 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1243 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1244 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1248 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1249 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1253 if (backup_path == NULL) {
1254 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1255 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1258 keep_backup = false;
1263 if (stat (backup_path, &statbuf) != -1) {
1264 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1265 ret = NOTMUCH_STATUS_FILE_ERROR;
1268 if (errno != ENOENT) {
1269 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1271 ret = NOTMUCH_STATUS_FILE_ERROR;
1275 /* Unconditionally attempt to remove old work-in-progress database (if
1276 * any). This is "protected" by database lock. If this fails due to write
1277 * errors (etc), the following code will fail and provide error message.
1279 (void) rmtree (compact_xapian_path);
1282 NotmuchCompactor compactor (status_cb, closure);
1283 notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0, compactor);
1284 } catch (const Xapian::Error &error) {
1285 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
1286 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1290 if (rename (xapian_path, backup_path)) {
1291 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1292 xapian_path, backup_path, strerror (errno));
1293 ret = NOTMUCH_STATUS_FILE_ERROR;
1297 if (rename (compact_xapian_path, xapian_path)) {
1298 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1299 compact_xapian_path, xapian_path, strerror (errno));
1300 ret = NOTMUCH_STATUS_FILE_ERROR;
1304 if (! keep_backup) {
1305 if (rmtree (backup_path)) {
1306 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1307 backup_path, strerror (errno));
1308 ret = NOTMUCH_STATUS_FILE_ERROR;
1315 notmuch_status_t ret2;
1317 const char *str = notmuch_database_status_string (notmuch);
1318 if (status_cb && str)
1319 status_cb (str, closure);
1321 ret2 = notmuch_database_destroy (notmuch);
1323 /* don't clobber previous error status */
1324 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1328 talloc_free (local);
1334 notmuch_database_destroy (notmuch_database_t *notmuch)
1336 notmuch_status_t status;
1338 status = notmuch_database_close (notmuch);
1340 delete notmuch->term_gen;
1341 notmuch->term_gen = NULL;
1342 delete notmuch->query_parser;
1343 notmuch->query_parser = NULL;
1344 delete notmuch->xapian_db;
1345 notmuch->xapian_db = NULL;
1346 delete notmuch->value_range_processor;
1347 notmuch->value_range_processor = NULL;
1348 delete notmuch->date_range_processor;
1349 notmuch->date_range_processor = NULL;
1350 delete notmuch->last_mod_range_processor;
1351 notmuch->last_mod_range_processor = NULL;
1353 talloc_free (notmuch);
1359 notmuch_database_get_path (notmuch_database_t *notmuch)
1361 return notmuch->path;
1365 notmuch_database_get_version (notmuch_database_t *notmuch)
1367 unsigned int version;
1368 string version_string;
1373 version_string = notmuch->xapian_db->get_metadata ("version");
1374 } catch (const Xapian::Error &error) {
1375 LOG_XAPIAN_EXCEPTION (notmuch, error);
1379 if (version_string.empty ())
1382 str = version_string.c_str ();
1383 if (str == NULL || *str == '\0')
1386 version = strtoul (str, &end, 10);
1388 INTERNAL_ERROR ("Malformed database version: %s", str);
1394 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1396 unsigned int version;
1398 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_WRITE)
1401 if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
1404 version = notmuch_database_get_version (notmuch);
1406 return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
1409 static volatile sig_atomic_t do_progress_notify = 0;
1412 handle_sigalrm (unused (int signal))
1414 do_progress_notify = 1;
1417 /* Upgrade the current database.
1419 * After opening a database in read-write mode, the client should
1420 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1421 * if so, upgrade with this function before making any modifications.
1423 * The optional progress_notify callback can be used by the caller to
1424 * provide progress indication to the user. If non-NULL it will be
1425 * called periodically with 'count' as the number of messages upgraded
1426 * so far and 'total' the overall number of messages that will be
1430 notmuch_database_upgrade (notmuch_database_t *notmuch,
1431 void (*progress_notify) (void *closure,
1435 void *local = talloc_new (NULL);
1436 Xapian::TermIterator t, t_end;
1437 Xapian::WritableDatabase *db;
1438 struct sigaction action;
1439 struct itimerval timerval;
1440 bool timer_is_active = false;
1441 enum _notmuch_features target_features, new_features;
1442 notmuch_status_t status;
1443 notmuch_private_status_t private_status;
1444 notmuch_query_t *query = NULL;
1445 unsigned int count = 0, total = 0;
1447 status = _notmuch_database_ensure_writable (notmuch);
1451 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1453 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1454 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1456 if (! notmuch_database_needs_upgrade (notmuch))
1457 return NOTMUCH_STATUS_SUCCESS;
1459 if (progress_notify) {
1460 /* Set up our handler for SIGALRM */
1461 memset (&action, 0, sizeof (struct sigaction));
1462 action.sa_handler = handle_sigalrm;
1463 sigemptyset (&action.sa_mask);
1464 action.sa_flags = SA_RESTART;
1465 sigaction (SIGALRM, &action, NULL);
1467 /* Then start a timer to send SIGALRM once per second. */
1468 timerval.it_interval.tv_sec = 1;
1469 timerval.it_interval.tv_usec = 0;
1470 timerval.it_value.tv_sec = 1;
1471 timerval.it_value.tv_usec = 0;
1472 setitimer (ITIMER_REAL, &timerval, NULL);
1474 timer_is_active = true;
1477 /* Figure out how much total work we need to do. */
1479 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1480 NOTMUCH_FEATURE_LAST_MOD)) {
1481 query = notmuch_query_create (notmuch, "");
1484 status = notmuch_query_count_messages (query, &msg_count);
1489 notmuch_query_destroy (query);
1492 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1493 t_end = db->allterms_end ("XTIMESTAMP");
1494 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1497 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1498 /* The ghost message upgrade converts all thread_id_*
1499 * metadata values into ghost message documents. */
1500 t_end = db->metadata_keys_end ("thread_id_");
1501 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1505 /* Perform the upgrade in a transaction. */
1506 db->begin_transaction (true);
1508 /* Set the target features so we write out changes in the desired
1510 notmuch->features = target_features;
1512 /* Perform per-message upgrades. */
1514 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1515 NOTMUCH_FEATURE_LAST_MOD)) {
1516 notmuch_messages_t *messages;
1517 notmuch_message_t *message;
1520 query = notmuch_query_create (notmuch, "");
1522 status = notmuch_query_search_messages (query, &messages);
1526 notmuch_messages_valid (messages);
1527 notmuch_messages_move_to_next (messages)) {
1528 if (do_progress_notify) {
1529 progress_notify (closure, (double) count / total);
1530 do_progress_notify = 0;
1533 message = notmuch_messages_get (messages);
1535 /* Before version 1, each message document had its
1536 * filename in the data field. Copy that into the new
1537 * format by calling notmuch_message_add_filename.
1539 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1540 filename = _notmuch_message_talloc_copy_data (message);
1541 if (filename && *filename != '\0') {
1542 _notmuch_message_add_filename (message, filename);
1543 _notmuch_message_clear_data (message);
1545 talloc_free (filename);
1548 /* Prior to version 2, the "folder:" prefix was
1549 * probabilistic and stemmed. Change it to the current
1550 * boolean prefix. Add "path:" prefixes while at it.
1552 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1553 _notmuch_message_upgrade_folder (message);
1555 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1556 * track modification revisions. Give all messages the
1557 * next available revision; since we just started tracking
1558 * revisions for this database, that will be 1.
1560 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1561 _notmuch_message_upgrade_last_mod (message);
1563 _notmuch_message_sync (message);
1565 notmuch_message_destroy (message);
1570 notmuch_query_destroy (query);
1574 /* Perform per-directory upgrades. */
1576 /* Before version 1 we stored directory timestamps in
1577 * XTIMESTAMP documents instead of the current XDIRECTORY
1578 * documents. So copy those as well. */
1579 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1580 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1582 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1585 Xapian::PostingIterator p, p_end;
1586 std::string term = *t;
1588 p_end = notmuch->xapian_db->postlist_end (term);
1590 for (p = notmuch->xapian_db->postlist_begin (term);
1593 Xapian::Document document;
1595 notmuch_directory_t *directory;
1597 if (do_progress_notify) {
1598 progress_notify (closure, (double) count / total);
1599 do_progress_notify = 0;
1602 document = find_document_for_doc_id (notmuch, *p);
1603 mtime = Xapian::sortable_unserialise (
1604 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1606 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1607 NOTMUCH_FIND_CREATE, &status);
1608 notmuch_directory_set_mtime (directory, mtime);
1609 notmuch_directory_destroy (directory);
1611 db->delete_document (*p);
1618 /* Perform metadata upgrades. */
1620 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1621 * messages were stored as database metadata. Change these to
1624 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1625 notmuch_message_t *message;
1626 std::string message_id, thread_id;
1628 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1629 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1631 if (do_progress_notify) {
1632 progress_notify (closure, (double) count / total);
1633 do_progress_notify = 0;
1636 message_id = (*t).substr (
1637 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1638 thread_id = db->get_metadata (*t);
1640 /* Create ghost message */
1641 message = _notmuch_message_create_for_message_id (
1642 notmuch, message_id.c_str (), &private_status);
1643 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1644 /* Document already exists; ignore the stored thread ID */
1645 } else if (private_status ==
1646 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1647 private_status = _notmuch_message_initialize_ghost (
1648 message, thread_id.c_str ());
1649 if (! private_status)
1650 _notmuch_message_sync (message);
1653 if (private_status) {
1654 _notmuch_database_log (notmuch,
1655 "Upgrade failed while creating ghost messages.\n");
1656 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1660 /* Clear saved metadata thread ID */
1661 db->set_metadata (*t, "");
1667 status = NOTMUCH_STATUS_SUCCESS;
1668 db->set_metadata ("features", _print_features (local, notmuch->features));
1669 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1672 if (status == NOTMUCH_STATUS_SUCCESS)
1673 db->commit_transaction ();
1675 db->cancel_transaction ();
1677 if (timer_is_active) {
1678 /* Now stop the timer. */
1679 timerval.it_interval.tv_sec = 0;
1680 timerval.it_interval.tv_usec = 0;
1681 timerval.it_value.tv_sec = 0;
1682 timerval.it_value.tv_usec = 0;
1683 setitimer (ITIMER_REAL, &timerval, NULL);
1685 /* And disable the signal handler. */
1686 action.sa_handler = SIG_IGN;
1687 sigaction (SIGALRM, &action, NULL);
1691 notmuch_query_destroy (query);
1693 talloc_free (local);
1698 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1700 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1701 notmuch->atomic_nesting > 0)
1704 if (notmuch_database_needs_upgrade (notmuch))
1705 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1708 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1709 } catch (const Xapian::Error &error) {
1710 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1711 error.get_msg ().c_str ());
1712 notmuch->exception_reported = true;
1713 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1717 notmuch->atomic_nesting++;
1718 return NOTMUCH_STATUS_SUCCESS;
1722 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1724 Xapian::WritableDatabase *db;
1726 if (notmuch->atomic_nesting == 0)
1727 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1729 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1730 notmuch->atomic_nesting > 1)
1733 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1735 db->commit_transaction ();
1737 /* This is a hack for testing. Xapian never flushes on a
1738 * non-flushed commit, even if the flush threshold is 1.
1739 * However, we rely on flushing to test atomicity. */
1740 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1741 if (thresh && atoi (thresh) == 1)
1743 } catch (const Xapian::Error &error) {
1744 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1745 error.get_msg ().c_str ());
1746 notmuch->exception_reported = true;
1747 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1750 if (notmuch->atomic_dirty) {
1751 ++notmuch->revision;
1752 notmuch->atomic_dirty = false;
1756 notmuch->atomic_nesting--;
1757 return NOTMUCH_STATUS_SUCCESS;
1761 notmuch_database_get_revision (notmuch_database_t *notmuch,
1765 *uuid = notmuch->uuid;
1766 return notmuch->revision;
1769 /* We allow the user to use arbitrarily long paths for directories. But
1770 * we have a term-length limit. So if we exceed that, we'll use the
1771 * SHA-1 of the path for the database term.
1773 * Note: This function may return the original value of 'path'. If it
1774 * does not, then the caller is responsible to free() the returned
1778 _notmuch_database_get_directory_db_path (const char *path)
1780 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1782 if (term_len > NOTMUCH_TERM_MAX)
1783 return _notmuch_sha1_of_string (path);
1788 /* Given a path, split it into two parts: the directory part is all
1789 * components except for the last, and the basename is that last
1790 * component. Getting the return-value for either part is optional
1791 * (the caller can pass NULL).
1793 * The original 'path' can represent either a regular file or a
1794 * directory---the splitting will be carried out in the same way in
1795 * either case. Trailing slashes on 'path' will be ignored, and any
1796 * cases of multiple '/' characters appearing in series will be
1797 * treated as a single '/'.
1799 * Allocation (if any) will have 'ctx' as the talloc owner. But
1800 * pointers will be returned within the original path string whenever
1803 * Note: If 'path' is non-empty and contains no non-trailing slash,
1804 * (that is, consists of a filename with no parent directory), then
1805 * the directory returned will be an empty string. However, if 'path'
1806 * is an empty string, then both directory and basename will be
1810 _notmuch_database_split_path (void *ctx,
1812 const char **directory,
1813 const char **basename)
1817 if (path == NULL || *path == '\0') {
1822 return NOTMUCH_STATUS_SUCCESS;
1825 /* Find the last slash (not counting a trailing slash), if any. */
1827 slash = path + strlen (path) - 1;
1829 /* First, skip trailing slashes. */
1830 while (slash != path && *slash == '/')
1833 /* Then, find a slash. */
1834 while (slash != path && *slash != '/') {
1841 /* Finally, skip multiple slashes. */
1842 while (slash != path && *(slash - 1) == '/')
1845 if (slash == path) {
1847 *directory = talloc_strdup (ctx, "");
1852 *directory = talloc_strndup (ctx, path, slash - path);
1855 return NOTMUCH_STATUS_SUCCESS;
1858 /* Find the document ID of the specified directory.
1860 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1861 * created if one does not exist for 'path'. Otherwise, if the
1862 * directory document does not exist, this sets *directory_id to
1863 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1866 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1868 notmuch_find_flags_t flags,
1869 unsigned int *directory_id)
1871 notmuch_directory_t *directory;
1872 notmuch_status_t status;
1876 return NOTMUCH_STATUS_SUCCESS;
1879 directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1880 if (status || ! directory) {
1885 *directory_id = _notmuch_directory_get_document_id (directory);
1887 notmuch_directory_destroy (directory);
1889 return NOTMUCH_STATUS_SUCCESS;
1893 _notmuch_database_get_directory_path (void *ctx,
1894 notmuch_database_t *notmuch,
1895 unsigned int doc_id)
1897 Xapian::Document document;
1899 document = find_document_for_doc_id (notmuch, doc_id);
1901 return talloc_strdup (ctx, document.get_data ().c_str ());
1904 /* Given a legal 'filename' for the database, (either relative to
1905 * database path or absolute with initial components identical to
1906 * database path), return a new string (with 'ctx' as the talloc
1907 * owner) suitable for use as a direntry term value.
1909 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1910 * will be created in the database as needed. Otherwise, if the
1911 * necessary directory documents do not exist, this sets
1912 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1915 _notmuch_database_filename_to_direntry (void *ctx,
1916 notmuch_database_t *notmuch,
1917 const char *filename,
1918 notmuch_find_flags_t flags,
1921 const char *relative, *directory, *basename;
1922 Xapian::docid directory_id;
1923 notmuch_status_t status;
1925 relative = _notmuch_database_relative_path (notmuch, filename);
1927 status = _notmuch_database_split_path (ctx, relative,
1928 &directory, &basename);
1932 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1934 if (status || directory_id == (unsigned int) -1) {
1939 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1941 return NOTMUCH_STATUS_SUCCESS;
1944 /* Given a legal 'path' for the database, return the relative path.
1946 * The return value will be a pointer to the original path contents,
1947 * and will be either the original string (if 'path' was relative) or
1948 * a portion of the string (if path was absolute and begins with the
1952 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1955 const char *db_path, *relative;
1956 unsigned int db_path_len;
1958 db_path = notmuch_database_get_path (notmuch);
1959 db_path_len = strlen (db_path);
1963 if (*relative == '/') {
1964 while (*relative == '/' && *(relative + 1) == '/')
1967 if (strncmp (relative, db_path, db_path_len) == 0) {
1968 relative += db_path_len;
1969 while (*relative == '/')
1978 notmuch_database_get_directory (notmuch_database_t *notmuch,
1980 notmuch_directory_t **directory)
1982 notmuch_status_t status;
1984 if (directory == NULL)
1985 return NOTMUCH_STATUS_NULL_POINTER;
1989 *directory = _notmuch_directory_find_or_create (notmuch, path,
1990 NOTMUCH_FIND_LOOKUP, &status);
1991 } catch (const Xapian::Error &error) {
1992 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1993 error.get_msg ().c_str ());
1994 notmuch->exception_reported = true;
1995 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2000 /* Allocate a document ID that satisfies the following criteria:
2002 * 1. The ID does not exist for any document in the Xapian database
2004 * 2. The ID was not previously returned from this function
2006 * 3. The ID is the smallest integer satisfying (1) and (2)
2008 * This function will trigger an internal error if these constraints
2009 * cannot all be satisfied, (that is, the pool of available document
2010 * IDs has been exhausted).
2013 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2015 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2017 notmuch->last_doc_id++;
2019 if (notmuch->last_doc_id == 0)
2020 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2022 return notmuch->last_doc_id;
2026 notmuch_database_remove_message (notmuch_database_t *notmuch,
2027 const char *filename)
2029 notmuch_status_t status;
2030 notmuch_message_t *message;
2032 status = notmuch_database_find_message_by_filename (notmuch, filename,
2035 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2036 status = _notmuch_message_remove_filename (message, filename);
2037 if (status == NOTMUCH_STATUS_SUCCESS)
2038 _notmuch_message_delete (message);
2039 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2040 _notmuch_message_sync (message);
2042 notmuch_message_destroy (message);
2049 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2050 const char *filename,
2051 notmuch_message_t **message_ret)
2054 const char *prefix = _find_prefix ("file-direntry");
2055 char *direntry, *term;
2056 Xapian::PostingIterator i, end;
2057 notmuch_status_t status;
2059 if (message_ret == NULL)
2060 return NOTMUCH_STATUS_NULL_POINTER;
2062 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2063 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2065 /* return NULL on any failure */
2066 *message_ret = NULL;
2068 local = talloc_new (notmuch);
2071 status = _notmuch_database_filename_to_direntry (
2072 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2073 if (status || ! direntry)
2076 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2078 find_doc_ids_for_term (notmuch, term, &i, &end);
2081 notmuch_private_status_t private_status;
2083 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2085 if (*message_ret == NULL)
2086 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2088 } catch (const Xapian::Error &error) {
2089 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2090 error.get_msg ().c_str ());
2091 notmuch->exception_reported = true;
2092 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2096 talloc_free (local);
2098 if (status && *message_ret) {
2099 notmuch_message_destroy (*message_ret);
2100 *message_ret = NULL;
2105 notmuch_string_list_t *
2106 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2107 Xapian::TermIterator &end,
2110 int prefix_len = strlen (prefix);
2111 notmuch_string_list_t *list;
2113 list = _notmuch_string_list_create (ctx);
2114 if (unlikely (list == NULL))
2117 for (i.skip_to (prefix); i != end; i++) {
2118 /* Terminate loop at first term without desired prefix. */
2119 if (strncmp ((*i).c_str (), prefix, prefix_len))
2122 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2129 notmuch_database_get_all_tags (notmuch_database_t *db)
2131 Xapian::TermIterator i, end;
2132 notmuch_string_list_t *tags;
2135 i = db->xapian_db->allterms_begin ();
2136 end = db->xapian_db->allterms_end ();
2137 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2138 _find_prefix ("tag"));
2139 _notmuch_string_list_sort (tags);
2140 return _notmuch_tags_create (db, tags);
2141 } catch (const Xapian::Error &error) {
2142 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2143 error.get_msg ().c_str ());
2144 db->exception_reported = true;
2150 notmuch_database_status_string (const notmuch_database_t *notmuch)
2152 return notmuch->status_string;