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->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
998 notmuch_database_destroy (notmuch);
1000 status = NOTMUCH_STATUS_FILE_ERROR;
1004 /* Check features. */
1005 incompat_features = NULL;
1006 notmuch->features = _parse_features (
1007 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1008 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1009 &incompat_features);
1010 if (incompat_features) {
1011 IGNORE_RESULT (asprintf (&message,
1012 "Error: Notmuch database at %s\n"
1013 " requires features (%s)\n"
1014 " not supported by this version of notmuch.\n",
1015 notmuch_path, incompat_features));
1016 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1017 notmuch_database_destroy (notmuch);
1019 status = NOTMUCH_STATUS_FILE_ERROR;
1023 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1024 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1025 if (last_thread_id.empty ()) {
1026 notmuch->last_thread_id = 0;
1031 str = last_thread_id.c_str ();
1032 notmuch->last_thread_id = strtoull (str, &end, 16);
1034 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1037 /* Get current highest revision number. */
1038 last_mod = notmuch->xapian_db->get_value_upper_bound (
1039 NOTMUCH_VALUE_LAST_MOD);
1040 if (last_mod.empty ())
1041 notmuch->revision = 0;
1043 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1044 notmuch->uuid = talloc_strdup (
1045 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1047 notmuch->query_parser = new Xapian::QueryParser;
1048 notmuch->term_gen = new Xapian::TermGenerator;
1049 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1050 notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1051 notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP, "date:");
1052 notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1053 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1054 notmuch->query_parser->set_database (*notmuch->xapian_db);
1055 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1056 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1057 notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
1058 notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
1059 notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
1061 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1062 const prefix_t *prefix = &prefix_table[i];
1063 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1064 _setup_query_field (prefix, notmuch);
1067 status = _setup_user_query_fields (notmuch);
1068 } catch (const Xapian::Error &error) {
1069 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1070 error.get_msg ().c_str ()));
1071 notmuch_database_destroy (notmuch);
1073 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1077 talloc_free (local);
1081 *status_string = message;
1087 *database = notmuch;
1089 talloc_free (notmuch);
1092 notmuch->open = true;
1098 notmuch_database_close (notmuch_database_t *notmuch)
1100 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1102 /* Many Xapian objects (and thus notmuch objects) hold references to
1103 * the database, so merely deleting the database may not suffice to
1104 * close it. Thus, we explicitly close it here. */
1105 if (notmuch->open) {
1107 /* If there's an outstanding transaction, it's unclear if
1108 * closing the Xapian database commits everything up to
1109 * that transaction, or may discard committed (but
1110 * unflushed) transactions. To be certain, explicitly
1111 * cancel any outstanding transaction before closing. */
1112 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1113 notmuch->atomic_nesting)
1114 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1115 ->cancel_transaction ();
1117 /* Close the database. This implicitly flushes
1118 * outstanding changes. */
1119 notmuch->xapian_db->close ();
1120 } catch (const Xapian::Error &error) {
1121 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1122 if (! notmuch->exception_reported) {
1123 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1124 error.get_msg ().c_str ());
1128 notmuch->open = false;
1133 _notmuch_database_reopen (notmuch_database_t *notmuch)
1135 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1136 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1139 notmuch->xapian_db->reopen ();
1140 } catch (const Xapian::Error &error) {
1141 if (! notmuch->exception_reported) {
1142 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1143 error.get_msg ().c_str ());
1144 notmuch->exception_reported = true;
1146 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1151 return NOTMUCH_STATUS_SUCCESS;
1155 unlink_cb (const char *path,
1156 unused (const struct stat *sb),
1158 unused (struct FTW *ftw))
1160 return remove (path);
1164 rmtree (const char *path)
1166 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1169 class NotmuchCompactor : public Xapian::Compactor
1171 notmuch_compact_status_cb_t status_cb;
1172 void *status_closure;
1175 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1176 status_cb (cb), status_closure (closure)
1181 set_status (const std::string &table, const std::string &status)
1185 if (status_cb == NULL)
1188 if (status.length () == 0)
1189 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
1191 msg = talloc_asprintf (NULL, " %s", status.c_str ());
1197 status_cb (msg, status_closure);
1202 /* Compacts the given database, optionally saving the original database
1203 * in backup_path. Additionally, a callback function can be provided to
1204 * give the user feedback on the progress of the (likely long-lived)
1205 * compaction process.
1207 * The backup path must point to a directory on the same volume as the
1208 * original database. Passing a NULL backup_path will result in the
1209 * uncompacted database being deleted after compaction has finished.
1210 * Note that the database write lock will be held during the
1211 * compaction process to protect data integrity.
1214 notmuch_database_compact (const char *path,
1215 const char *backup_path,
1216 notmuch_compact_status_cb_t status_cb,
1220 char *notmuch_path, *xapian_path, *compact_xapian_path;
1221 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1222 notmuch_database_t *notmuch = NULL;
1223 struct stat statbuf;
1225 char *message = NULL;
1227 local = talloc_new (NULL);
1229 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1231 ret = notmuch_database_open_verbose (path,
1232 NOTMUCH_DATABASE_MODE_READ_WRITE,
1236 if (status_cb) status_cb (message, closure);
1240 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1241 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1245 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1246 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1250 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1251 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1255 if (backup_path == NULL) {
1256 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1257 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1260 keep_backup = false;
1265 if (stat (backup_path, &statbuf) != -1) {
1266 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1267 ret = NOTMUCH_STATUS_FILE_ERROR;
1270 if (errno != ENOENT) {
1271 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1273 ret = NOTMUCH_STATUS_FILE_ERROR;
1277 /* Unconditionally attempt to remove old work-in-progress database (if
1278 * any). This is "protected" by database lock. If this fails due to write
1279 * errors (etc), the following code will fail and provide error message.
1281 (void) rmtree (compact_xapian_path);
1284 NotmuchCompactor compactor (status_cb, closure);
1285 notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0, compactor);
1286 } catch (const Xapian::Error &error) {
1287 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
1288 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1292 if (rename (xapian_path, backup_path)) {
1293 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1294 xapian_path, backup_path, strerror (errno));
1295 ret = NOTMUCH_STATUS_FILE_ERROR;
1299 if (rename (compact_xapian_path, xapian_path)) {
1300 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1301 compact_xapian_path, xapian_path, strerror (errno));
1302 ret = NOTMUCH_STATUS_FILE_ERROR;
1306 if (! keep_backup) {
1307 if (rmtree (backup_path)) {
1308 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1309 backup_path, strerror (errno));
1310 ret = NOTMUCH_STATUS_FILE_ERROR;
1317 notmuch_status_t ret2;
1319 const char *str = notmuch_database_status_string (notmuch);
1320 if (status_cb && str)
1321 status_cb (str, closure);
1323 ret2 = notmuch_database_destroy (notmuch);
1325 /* don't clobber previous error status */
1326 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1330 talloc_free (local);
1336 notmuch_database_destroy (notmuch_database_t *notmuch)
1338 notmuch_status_t status;
1340 status = notmuch_database_close (notmuch);
1342 delete notmuch->term_gen;
1343 notmuch->term_gen = NULL;
1344 delete notmuch->query_parser;
1345 notmuch->query_parser = NULL;
1346 delete notmuch->xapian_db;
1347 notmuch->xapian_db = NULL;
1348 delete notmuch->value_range_processor;
1349 notmuch->value_range_processor = NULL;
1350 delete notmuch->date_range_processor;
1351 notmuch->date_range_processor = NULL;
1352 delete notmuch->last_mod_range_processor;
1353 notmuch->last_mod_range_processor = NULL;
1355 talloc_free (notmuch);
1361 notmuch_database_get_path (notmuch_database_t *notmuch)
1363 return notmuch->path;
1367 notmuch_database_get_version (notmuch_database_t *notmuch)
1369 unsigned int version;
1370 string version_string;
1375 version_string = notmuch->xapian_db->get_metadata ("version");
1376 } catch (const Xapian::Error &error) {
1377 LOG_XAPIAN_EXCEPTION (notmuch, error);
1381 if (version_string.empty ())
1384 str = version_string.c_str ();
1385 if (str == NULL || *str == '\0')
1388 version = strtoul (str, &end, 10);
1390 INTERNAL_ERROR ("Malformed database version: %s", str);
1396 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1398 unsigned int version;
1400 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_WRITE)
1403 if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
1406 version = notmuch_database_get_version (notmuch);
1408 return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
1411 static volatile sig_atomic_t do_progress_notify = 0;
1414 handle_sigalrm (unused (int signal))
1416 do_progress_notify = 1;
1419 /* Upgrade the current database.
1421 * After opening a database in read-write mode, the client should
1422 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1423 * if so, upgrade with this function before making any modifications.
1425 * The optional progress_notify callback can be used by the caller to
1426 * provide progress indication to the user. If non-NULL it will be
1427 * called periodically with 'count' as the number of messages upgraded
1428 * so far and 'total' the overall number of messages that will be
1432 notmuch_database_upgrade (notmuch_database_t *notmuch,
1433 void (*progress_notify) (void *closure,
1437 void *local = talloc_new (NULL);
1438 Xapian::TermIterator t, t_end;
1439 Xapian::WritableDatabase *db;
1440 struct sigaction action;
1441 struct itimerval timerval;
1442 bool timer_is_active = false;
1443 enum _notmuch_features target_features, new_features;
1444 notmuch_status_t status;
1445 notmuch_private_status_t private_status;
1446 notmuch_query_t *query = NULL;
1447 unsigned int count = 0, total = 0;
1449 status = _notmuch_database_ensure_writable (notmuch);
1453 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1455 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1456 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1458 if (! notmuch_database_needs_upgrade (notmuch))
1459 return NOTMUCH_STATUS_SUCCESS;
1461 if (progress_notify) {
1462 /* Set up our handler for SIGALRM */
1463 memset (&action, 0, sizeof (struct sigaction));
1464 action.sa_handler = handle_sigalrm;
1465 sigemptyset (&action.sa_mask);
1466 action.sa_flags = SA_RESTART;
1467 sigaction (SIGALRM, &action, NULL);
1469 /* Then start a timer to send SIGALRM once per second. */
1470 timerval.it_interval.tv_sec = 1;
1471 timerval.it_interval.tv_usec = 0;
1472 timerval.it_value.tv_sec = 1;
1473 timerval.it_value.tv_usec = 0;
1474 setitimer (ITIMER_REAL, &timerval, NULL);
1476 timer_is_active = true;
1479 /* Figure out how much total work we need to do. */
1481 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1482 NOTMUCH_FEATURE_LAST_MOD)) {
1483 query = notmuch_query_create (notmuch, "");
1486 status = notmuch_query_count_messages (query, &msg_count);
1491 notmuch_query_destroy (query);
1494 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1495 t_end = db->allterms_end ("XTIMESTAMP");
1496 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1499 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1500 /* The ghost message upgrade converts all thread_id_*
1501 * metadata values into ghost message documents. */
1502 t_end = db->metadata_keys_end ("thread_id_");
1503 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1507 /* Perform the upgrade in a transaction. */
1508 db->begin_transaction (true);
1510 /* Set the target features so we write out changes in the desired
1512 notmuch->features = target_features;
1514 /* Perform per-message upgrades. */
1516 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1517 NOTMUCH_FEATURE_LAST_MOD)) {
1518 notmuch_messages_t *messages;
1519 notmuch_message_t *message;
1522 query = notmuch_query_create (notmuch, "");
1524 status = notmuch_query_search_messages (query, &messages);
1528 notmuch_messages_valid (messages);
1529 notmuch_messages_move_to_next (messages)) {
1530 if (do_progress_notify) {
1531 progress_notify (closure, (double) count / total);
1532 do_progress_notify = 0;
1535 message = notmuch_messages_get (messages);
1537 /* Before version 1, each message document had its
1538 * filename in the data field. Copy that into the new
1539 * format by calling notmuch_message_add_filename.
1541 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1542 filename = _notmuch_message_talloc_copy_data (message);
1543 if (filename && *filename != '\0') {
1544 _notmuch_message_add_filename (message, filename);
1545 _notmuch_message_clear_data (message);
1547 talloc_free (filename);
1550 /* Prior to version 2, the "folder:" prefix was
1551 * probabilistic and stemmed. Change it to the current
1552 * boolean prefix. Add "path:" prefixes while at it.
1554 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1555 _notmuch_message_upgrade_folder (message);
1557 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1558 * track modification revisions. Give all messages the
1559 * next available revision; since we just started tracking
1560 * revisions for this database, that will be 1.
1562 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1563 _notmuch_message_upgrade_last_mod (message);
1565 _notmuch_message_sync (message);
1567 notmuch_message_destroy (message);
1572 notmuch_query_destroy (query);
1576 /* Perform per-directory upgrades. */
1578 /* Before version 1 we stored directory timestamps in
1579 * XTIMESTAMP documents instead of the current XDIRECTORY
1580 * documents. So copy those as well. */
1581 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1582 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1584 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1587 Xapian::PostingIterator p, p_end;
1588 std::string term = *t;
1590 p_end = notmuch->xapian_db->postlist_end (term);
1592 for (p = notmuch->xapian_db->postlist_begin (term);
1595 Xapian::Document document;
1597 notmuch_directory_t *directory;
1599 if (do_progress_notify) {
1600 progress_notify (closure, (double) count / total);
1601 do_progress_notify = 0;
1604 document = find_document_for_doc_id (notmuch, *p);
1605 mtime = Xapian::sortable_unserialise (
1606 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1608 directory = _notmuch_directory_create (notmuch, term.c_str () + 10,
1609 NOTMUCH_FIND_CREATE, &status);
1610 notmuch_directory_set_mtime (directory, mtime);
1611 notmuch_directory_destroy (directory);
1613 db->delete_document (*p);
1620 /* Perform metadata upgrades. */
1622 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1623 * messages were stored as database metadata. Change these to
1626 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1627 notmuch_message_t *message;
1628 std::string message_id, thread_id;
1630 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1631 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1633 if (do_progress_notify) {
1634 progress_notify (closure, (double) count / total);
1635 do_progress_notify = 0;
1638 message_id = (*t).substr (
1639 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1640 thread_id = db->get_metadata (*t);
1642 /* Create ghost message */
1643 message = _notmuch_message_create_for_message_id (
1644 notmuch, message_id.c_str (), &private_status);
1645 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1646 /* Document already exists; ignore the stored thread ID */
1647 } else if (private_status ==
1648 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1649 private_status = _notmuch_message_initialize_ghost (
1650 message, thread_id.c_str ());
1651 if (! private_status)
1652 _notmuch_message_sync (message);
1655 if (private_status) {
1656 _notmuch_database_log (notmuch,
1657 "Upgrade failed while creating ghost messages.\n");
1658 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1662 /* Clear saved metadata thread ID */
1663 db->set_metadata (*t, "");
1669 status = NOTMUCH_STATUS_SUCCESS;
1670 db->set_metadata ("features", _print_features (local, notmuch->features));
1671 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1674 if (status == NOTMUCH_STATUS_SUCCESS)
1675 db->commit_transaction ();
1677 db->cancel_transaction ();
1679 if (timer_is_active) {
1680 /* Now stop the timer. */
1681 timerval.it_interval.tv_sec = 0;
1682 timerval.it_interval.tv_usec = 0;
1683 timerval.it_value.tv_sec = 0;
1684 timerval.it_value.tv_usec = 0;
1685 setitimer (ITIMER_REAL, &timerval, NULL);
1687 /* And disable the signal handler. */
1688 action.sa_handler = SIG_IGN;
1689 sigaction (SIGALRM, &action, NULL);
1693 notmuch_query_destroy (query);
1695 talloc_free (local);
1700 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1702 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1703 notmuch->atomic_nesting > 0)
1706 if (notmuch_database_needs_upgrade (notmuch))
1707 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1710 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1711 } catch (const Xapian::Error &error) {
1712 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1713 error.get_msg ().c_str ());
1714 notmuch->exception_reported = true;
1715 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1719 notmuch->atomic_nesting++;
1720 return NOTMUCH_STATUS_SUCCESS;
1724 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1726 Xapian::WritableDatabase *db;
1728 if (notmuch->atomic_nesting == 0)
1729 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1731 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1732 notmuch->atomic_nesting > 1)
1735 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1737 db->commit_transaction ();
1739 /* This is a hack for testing. Xapian never flushes on a
1740 * non-flushed commit, even if the flush threshold is 1.
1741 * However, we rely on flushing to test atomicity. */
1742 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1743 if (thresh && atoi (thresh) == 1)
1745 } catch (const Xapian::Error &error) {
1746 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1747 error.get_msg ().c_str ());
1748 notmuch->exception_reported = true;
1749 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1752 if (notmuch->atomic_dirty) {
1753 ++notmuch->revision;
1754 notmuch->atomic_dirty = false;
1758 notmuch->atomic_nesting--;
1759 return NOTMUCH_STATUS_SUCCESS;
1763 notmuch_database_get_revision (notmuch_database_t *notmuch,
1767 *uuid = notmuch->uuid;
1768 return notmuch->revision;
1771 /* We allow the user to use arbitrarily long paths for directories. But
1772 * we have a term-length limit. So if we exceed that, we'll use the
1773 * SHA-1 of the path for the database term.
1775 * Note: This function may return the original value of 'path'. If it
1776 * does not, then the caller is responsible to free() the returned
1780 _notmuch_database_get_directory_db_path (const char *path)
1782 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1784 if (term_len > NOTMUCH_TERM_MAX)
1785 return _notmuch_sha1_of_string (path);
1790 /* Given a path, split it into two parts: the directory part is all
1791 * components except for the last, and the basename is that last
1792 * component. Getting the return-value for either part is optional
1793 * (the caller can pass NULL).
1795 * The original 'path' can represent either a regular file or a
1796 * directory---the splitting will be carried out in the same way in
1797 * either case. Trailing slashes on 'path' will be ignored, and any
1798 * cases of multiple '/' characters appearing in series will be
1799 * treated as a single '/'.
1801 * Allocation (if any) will have 'ctx' as the talloc owner. But
1802 * pointers will be returned within the original path string whenever
1805 * Note: If 'path' is non-empty and contains no non-trailing slash,
1806 * (that is, consists of a filename with no parent directory), then
1807 * the directory returned will be an empty string. However, if 'path'
1808 * is an empty string, then both directory and basename will be
1812 _notmuch_database_split_path (void *ctx,
1814 const char **directory,
1815 const char **basename)
1819 if (path == NULL || *path == '\0') {
1824 return NOTMUCH_STATUS_SUCCESS;
1827 /* Find the last slash (not counting a trailing slash), if any. */
1829 slash = path + strlen (path) - 1;
1831 /* First, skip trailing slashes. */
1832 while (slash != path && *slash == '/')
1835 /* Then, find a slash. */
1836 while (slash != path && *slash != '/') {
1843 /* Finally, skip multiple slashes. */
1844 while (slash != path && *(slash - 1) == '/')
1847 if (slash == path) {
1849 *directory = talloc_strdup (ctx, "");
1854 *directory = talloc_strndup (ctx, path, slash - path);
1857 return NOTMUCH_STATUS_SUCCESS;
1860 /* Find the document ID of the specified directory.
1862 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1863 * created if one does not exist for 'path'. Otherwise, if the
1864 * directory document does not exist, this sets *directory_id to
1865 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1868 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1870 notmuch_find_flags_t flags,
1871 unsigned int *directory_id)
1873 notmuch_directory_t *directory;
1874 notmuch_status_t status;
1878 return NOTMUCH_STATUS_SUCCESS;
1881 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1882 if (status || ! directory) {
1887 *directory_id = _notmuch_directory_get_document_id (directory);
1889 notmuch_directory_destroy (directory);
1891 return NOTMUCH_STATUS_SUCCESS;
1895 _notmuch_database_get_directory_path (void *ctx,
1896 notmuch_database_t *notmuch,
1897 unsigned int doc_id)
1899 Xapian::Document document;
1901 document = find_document_for_doc_id (notmuch, doc_id);
1903 return talloc_strdup (ctx, document.get_data ().c_str ());
1906 /* Given a legal 'filename' for the database, (either relative to
1907 * database path or absolute with initial components identical to
1908 * database path), return a new string (with 'ctx' as the talloc
1909 * owner) suitable for use as a direntry term value.
1911 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1912 * will be created in the database as needed. Otherwise, if the
1913 * necessary directory documents do not exist, this sets
1914 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1917 _notmuch_database_filename_to_direntry (void *ctx,
1918 notmuch_database_t *notmuch,
1919 const char *filename,
1920 notmuch_find_flags_t flags,
1923 const char *relative, *directory, *basename;
1924 Xapian::docid directory_id;
1925 notmuch_status_t status;
1927 relative = _notmuch_database_relative_path (notmuch, filename);
1929 status = _notmuch_database_split_path (ctx, relative,
1930 &directory, &basename);
1934 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1936 if (status || directory_id == (unsigned int) -1) {
1941 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1943 return NOTMUCH_STATUS_SUCCESS;
1946 /* Given a legal 'path' for the database, return the relative path.
1948 * The return value will be a pointer to the original path contents,
1949 * and will be either the original string (if 'path' was relative) or
1950 * a portion of the string (if path was absolute and begins with the
1954 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1957 const char *db_path, *relative;
1958 unsigned int db_path_len;
1960 db_path = notmuch_database_get_path (notmuch);
1961 db_path_len = strlen (db_path);
1965 if (*relative == '/') {
1966 while (*relative == '/' && *(relative + 1) == '/')
1969 if (strncmp (relative, db_path, db_path_len) == 0) {
1970 relative += db_path_len;
1971 while (*relative == '/')
1980 notmuch_database_get_directory (notmuch_database_t *notmuch,
1982 notmuch_directory_t **directory)
1984 notmuch_status_t status;
1986 if (directory == NULL)
1987 return NOTMUCH_STATUS_NULL_POINTER;
1991 *directory = _notmuch_directory_create (notmuch, path,
1992 NOTMUCH_FIND_LOOKUP, &status);
1993 } catch (const Xapian::Error &error) {
1994 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1995 error.get_msg ().c_str ());
1996 notmuch->exception_reported = true;
1997 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2002 /* Allocate a document ID that satisfies the following criteria:
2004 * 1. The ID does not exist for any document in the Xapian database
2006 * 2. The ID was not previously returned from this function
2008 * 3. The ID is the smallest integer satisfying (1) and (2)
2010 * This function will trigger an internal error if these constraints
2011 * cannot all be satisfied, (that is, the pool of available document
2012 * IDs has been exhausted).
2015 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2017 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2019 notmuch->last_doc_id++;
2021 if (notmuch->last_doc_id == 0)
2022 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2024 return notmuch->last_doc_id;
2028 notmuch_database_remove_message (notmuch_database_t *notmuch,
2029 const char *filename)
2031 notmuch_status_t status;
2032 notmuch_message_t *message;
2034 status = notmuch_database_find_message_by_filename (notmuch, filename,
2037 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2038 status = _notmuch_message_remove_filename (message, filename);
2039 if (status == NOTMUCH_STATUS_SUCCESS)
2040 _notmuch_message_delete (message);
2041 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2042 _notmuch_message_sync (message);
2044 notmuch_message_destroy (message);
2051 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2052 const char *filename,
2053 notmuch_message_t **message_ret)
2056 const char *prefix = _find_prefix ("file-direntry");
2057 char *direntry, *term;
2058 Xapian::PostingIterator i, end;
2059 notmuch_status_t status;
2061 if (message_ret == NULL)
2062 return NOTMUCH_STATUS_NULL_POINTER;
2064 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2065 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2067 /* return NULL on any failure */
2068 *message_ret = NULL;
2070 local = talloc_new (notmuch);
2073 status = _notmuch_database_filename_to_direntry (
2074 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2075 if (status || ! direntry)
2078 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2080 find_doc_ids_for_term (notmuch, term, &i, &end);
2083 notmuch_private_status_t private_status;
2085 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2087 if (*message_ret == NULL)
2088 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2090 } catch (const Xapian::Error &error) {
2091 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2092 error.get_msg ().c_str ());
2093 notmuch->exception_reported = true;
2094 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2098 talloc_free (local);
2100 if (status && *message_ret) {
2101 notmuch_message_destroy (*message_ret);
2102 *message_ret = NULL;
2107 notmuch_string_list_t *
2108 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2109 Xapian::TermIterator &end,
2112 int prefix_len = strlen (prefix);
2113 notmuch_string_list_t *list;
2115 list = _notmuch_string_list_create (ctx);
2116 if (unlikely (list == NULL))
2119 for (i.skip_to (prefix); i != end; i++) {
2120 /* Terminate loop at first term without desired prefix. */
2121 if (strncmp ((*i).c_str (), prefix, prefix_len))
2124 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2131 notmuch_database_get_all_tags (notmuch_database_t *db)
2133 Xapian::TermIterator i, end;
2134 notmuch_string_list_t *tags;
2137 i = db->xapian_db->allterms_begin ();
2138 end = db->xapian_db->allterms_end ();
2139 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2140 _find_prefix ("tag"));
2141 _notmuch_string_list_sort (tags);
2142 return _notmuch_tags_create (db, tags);
2143 } catch (const Xapian::Error &error) {
2144 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2145 error.get_msg ().c_str ());
2146 db->exception_reported = true;
2152 notmuch_database_status_string (const notmuch_database_t *notmuch)
2154 return notmuch->status_string;