1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "thread-fp.h"
25 #include "regexp-fields.h"
26 #include "string-util.h"
35 #include <glib.h> /* g_free, GPtrArray, GHashTable */
36 #include <glib-object.h> /* g_type_init */
38 #include <gmime/gmime.h> /* g_mime_init */
42 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
47 notmuch_field_flag_t flags;
50 #define NOTMUCH_DATABASE_VERSION 3
52 #define STRINGIFY(s) _SUB_STRINGIFY (s)
53 #define _SUB_STRINGIFY(s) #s
55 #if HAVE_XAPIAN_DB_RETRY_LOCK
56 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
58 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
61 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
63 * We currently have three different types of documents (mail, ghost,
64 * and directory) and also some metadata.
66 * There are two kinds of prefixes used in notmuch. There are the
67 * human friendly 'prefix names' like "thread:", which are also used
68 * in the query parser, and the actual prefix terms in the database
69 * (e.g. "G"). The correspondence is maintained in the file scope data
70 * structure 'prefix_table'.
74 * A mail document is associated with a particular email message. It
75 * is stored in one or more files on disk and is uniquely identified
76 * by its "id" field (which is generally the message ID). It is
77 * indexed with the following prefixed terms which the database uses
78 * to construct threads, etc.:
80 * Single terms of given prefix:
84 * id: Unique ID of mail. This is from the Message-ID header
85 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
86 * If it's present and too long, then we use
87 * "notmuch-sha1-<sha1_sum_of_message_id>".
88 * If this header is not present, we use
89 * "notmuch-sha1-<sha1_sum_of_entire_file>".
91 * thread: The ID of the thread to which the mail belongs
93 * replyto: The ID from the In-Reply-To header of the mail (if any).
95 * Multiple terms of given prefix:
97 * reference: All message IDs from In-Reply-To and References
98 * headers in the message.
100 * tag: Any tags associated with this message by the user.
102 * file-direntry: A colon-separated pair of values
103 * (INTEGER:STRING), where INTEGER is the
104 * document ID of a directory document, and
105 * STRING is the name of a file within that
106 * directory for this mail message.
108 * property: Has a property with key=value
109 * FIXME: if no = is present, should match on any value
111 * A mail document also has four values:
113 * TIMESTAMP: The time_t value corresponding to the message's
116 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
118 * FROM: The value of the "From" header
120 * SUBJECT: The value of the "Subject" header
122 * LAST_MOD: The revision number as of the last tag or
125 * The prefixed terms described above are also searchable without an
126 * explicit field name, but as of notmuch 0.29 this is due to
127 * query-parser setup, not extra terms in the database. In addition,
128 * terms from the content of the message are added without a prefix
129 * for use by the user in searching. Note that the prefix name "body"
130 * is used to refer to the empty prefix string in the database.
132 * The path of the containing folder is added with the "folder" prefix
133 * (see _notmuch_message_add_folder_terms). Sub-paths of the the path
134 * of the mail message are added with the "path" prefix.
136 * The data portion of a mail document is empty.
138 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
139 * -----------------------------------------------
140 * A ghost mail document is like a mail document, but where we don't
141 * have the message content. These are used to track thread reference
142 * information for messages we haven't received.
144 * A ghost mail document has type: ghost; id and thread fields that
145 * are identical to the mail document fields; and a MESSAGE_ID value.
149 * A directory document is used by a client of the notmuch library to
150 * maintain data necessary to allow for efficient polling of mail
153 * All directory documents contain one term:
155 * directory: The directory path (relative to the database path)
156 * Or the SHA1 sum of the directory path (if the
157 * path itself is too long to fit in a Xapian
160 * And all directory documents for directories other than top-level
161 * directories also contain the following term:
163 * directory-direntry: A colon-separated pair of values
164 * (INTEGER:STRING), where INTEGER is the
165 * document ID of the parent directory
166 * document, and STRING is the name of this
167 * directory within that parent.
169 * All directory documents have a single value:
171 * TIMESTAMP: The mtime of the directory (at last scan)
173 * The data portion of a directory document contains the path of the
174 * directory (relative to the database path).
178 * Xapian allows us to store arbitrary name-value pairs as
179 * "metadata". We currently use the following metadata names with the
182 * version The database schema version, (which is distinct
183 * from both the notmuch package version (see
184 * notmuch --version) and the libnotmuch library
185 * version. The version is stored as an base-10
186 * ASCII integer. The initial database version
187 * was 1, (though a schema existed before that
188 * were no "version" database value existed at
189 * all). Successive versions are allocated as
190 * changes are made to the database (such as by
191 * indexing new fields).
193 * features The set of features supported by this
194 * database. This consists of a set of
195 * '\n'-separated lines, where each is a feature
196 * name, a '\t', and compatibility flags. If the
197 * compatibility flags contain 'w', then the
198 * opener must support this feature to safely
199 * write this database. If the compatibility
200 * flags contain 'r', then the opener must
201 * support this feature to read this database.
202 * Introduced in database version 3.
204 * last_thread_id The last thread ID generated. This is stored
205 * as a 16-byte hexadecimal ASCII representation
206 * of a 64-bit unsigned integer. The first ID
207 * generated is 1 and the value will be
208 * incremented for each thread ID.
210 * C* metadata keys starting with C indicate
211 * configuration data. It can be managed with the
212 * n_database_*config* API. There is a convention
213 * of hierarchical keys separated by '.' (e.g.
214 * query.notmuch stores the value for the named
215 * query 'notmuch'), but it is not enforced by the
221 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
222 * Instead, the database has the following additional database
225 * thread_id_* A pre-allocated thread ID for a particular
226 * message. This is actually an arbitrarily large
227 * family of metadata name. Any particular name is
228 * formed by concatenating "thread_id_" with a message
229 * ID (or the SHA1 sum of a message ID if it is very
230 * long---see description of 'id' in the mail
231 * document). The value stored is a thread ID.
233 * These thread ID metadata values are stored
234 * whenever a message references a parent message
235 * that does not yet exist in the database. A
236 * thread ID will be allocated and stored, and if
237 * the message is later added, the stored thread
238 * ID will be used (and the metadata value will
241 * Even before a message is added, it's
242 * pre-allocated thread ID is useful so that all
243 * descendant messages that reference this common
244 * parent can be recognized as belonging to the
248 /* With these prefix values we follow the conventions published here:
250 * https://xapian.org/docs/omega/termprefixes.html
252 * as much as makes sense. Note that I took some liberty in matching
253 * the reserved prefix values to notmuch concepts, (for example, 'G'
254 * is documented as "newsGroup (or similar entity - e.g. a web forum
255 * name)", for which I think the thread is the closest analogue in
256 * notmuch. This in spite of the fact that we will eventually be
257 * storing mailing-list messages where 'G' for "mailing list name"
258 * might be even a closer analogue. I'm treating the single-character
259 * prefixes preferentially for core notmuch concepts (which will be
260 * nearly universal to all mail messages).
264 prefix_t prefix_table[] = {
265 /* name term prefix flags */
266 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
267 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
268 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
269 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
270 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
271 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
272 { "body", "", NOTMUCH_FIELD_EXTERNAL |
273 NOTMUCH_FIELD_PROBABILISTIC },
274 { "thread", "G", NOTMUCH_FIELD_EXTERNAL |
275 NOTMUCH_FIELD_PROCESSOR },
276 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
277 NOTMUCH_FIELD_PROCESSOR },
278 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
279 NOTMUCH_FIELD_PROCESSOR },
280 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
281 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
282 NOTMUCH_FIELD_PROCESSOR },
283 { "path", "P", NOTMUCH_FIELD_EXTERNAL |
284 NOTMUCH_FIELD_PROCESSOR },
285 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
287 * Unconditionally add ':' to reduce potential ambiguity with
288 * overlapping prefixes and/or terms that start with capital
289 * letters. See Xapian document termprefixes.html for related
292 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
293 NOTMUCH_FIELD_PROCESSOR },
294 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
295 NOTMUCH_FIELD_PROCESSOR },
296 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
297 NOTMUCH_FIELD_PROCESSOR },
298 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
299 NOTMUCH_FIELD_PROBABILISTIC |
300 NOTMUCH_FIELD_PROCESSOR },
301 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
302 NOTMUCH_FIELD_PROBABILISTIC },
303 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
304 NOTMUCH_FIELD_PROBABILISTIC },
305 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
306 NOTMUCH_FIELD_PROBABILISTIC },
307 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
308 NOTMUCH_FIELD_PROBABILISTIC |
309 NOTMUCH_FIELD_PROCESSOR },
313 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
316 notmuch->query_parser->add_prefix ("", prefix->prefix);
317 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
318 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
320 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
323 notmuch_string_map_iterator_t *
324 _notmuch_database_user_headers (notmuch_database_t *notmuch)
326 return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
330 _user_prefix (void *ctx, const char *name)
332 return talloc_asprintf (ctx, "XU%s:", name);
335 static notmuch_status_t
336 _setup_user_query_fields (notmuch_database_t *notmuch)
338 notmuch_config_list_t *list;
339 notmuch_status_t status;
341 notmuch->user_prefix = _notmuch_string_map_create (notmuch);
342 if (notmuch->user_prefix == NULL)
343 return NOTMUCH_STATUS_OUT_OF_MEMORY;
345 notmuch->user_header = _notmuch_string_map_create (notmuch);
346 if (notmuch->user_header == NULL)
347 return NOTMUCH_STATUS_OUT_OF_MEMORY;
349 status = notmuch_database_get_config_list (notmuch, CONFIG_HEADER_PREFIX, &list);
353 for (; notmuch_config_list_valid (list); notmuch_config_list_move_to_next (list)) {
355 prefix_t query_field;
357 const char *key = notmuch_config_list_key (list)
358 + sizeof (CONFIG_HEADER_PREFIX) - 1;
360 _notmuch_string_map_append (notmuch->user_prefix,
362 _user_prefix (notmuch, key));
364 _notmuch_string_map_append (notmuch->user_header,
366 notmuch_config_list_value (list));
368 query_field.name = talloc_strdup (notmuch, key);
369 query_field.prefix = _user_prefix (notmuch, key);
370 query_field.flags = NOTMUCH_FIELD_PROBABILISTIC
371 | NOTMUCH_FIELD_EXTERNAL;
373 _setup_query_field_default (&query_field, notmuch);
376 notmuch_config_list_destroy (list);
378 return NOTMUCH_STATUS_SUCCESS;
382 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
384 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
385 Xapian::FieldProcessor *fp;
387 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
388 fp = (new DateFieldProcessor(NOTMUCH_VALUE_TIMESTAMP))->release ();
389 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
390 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
391 else if (STRNCMP_LITERAL (prefix->name, "thread") == 0)
392 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
394 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
395 *notmuch->query_parser, notmuch))->release ();
397 /* we treat all field-processor fields as boolean in order to get the raw input */
399 notmuch->query_parser->add_prefix ("", prefix->prefix);
400 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
402 _setup_query_field_default (prefix, notmuch);
407 _find_prefix (const char *name)
411 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
412 if (strcmp (name, prefix_table[i].name) == 0)
413 return prefix_table[i].prefix;
416 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
421 /* Like find prefix, but include the possibility of user defined
422 * prefixes specific to this database */
425 _notmuch_database_prefix (notmuch_database_t *notmuch, const char *name)
429 /*XXX TODO: reduce code duplication */
430 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
431 if (strcmp (name, prefix_table[i].name) == 0)
432 return prefix_table[i].prefix;
435 if (notmuch->user_prefix)
436 return _notmuch_string_map_get (notmuch->user_prefix, name);
441 static const struct {
442 /* NOTMUCH_FEATURE_* value. */
443 _notmuch_features value;
444 /* Feature name as it appears in the database. This name should
445 * be appropriate for displaying to the user if an older version
446 * of notmuch doesn't support this feature. */
448 /* Compatibility flags when this feature is declared. */
450 } feature_names[] = {
451 { NOTMUCH_FEATURE_FILE_TERMS,
452 "multiple paths per message", "rw" },
453 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
454 "relative directory paths", "rw" },
455 /* Header values are not required for reading a database because a
456 * reader can just refer to the message file. */
457 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
458 "from/subject/message-ID in database", "w" },
459 { NOTMUCH_FEATURE_BOOL_FOLDER,
460 "exact folder:/path: search", "rw" },
461 { NOTMUCH_FEATURE_GHOSTS,
462 "mail documents for missing messages", "w" },
463 /* Knowledge of the index mime-types are not required for reading
464 * a database because a reader will just be unable to query
466 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
467 "indexed MIME types", "w" },
468 { NOTMUCH_FEATURE_LAST_MOD,
469 "modification tracking", "w" },
470 /* Existing databases will work fine for all queries not involving
472 { NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY,
473 "index body and headers separately", "w" },
477 notmuch_status_to_string (notmuch_status_t status)
480 case NOTMUCH_STATUS_SUCCESS:
481 return "No error occurred";
482 case NOTMUCH_STATUS_OUT_OF_MEMORY:
483 return "Out of memory";
484 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
485 return "Attempt to write to a read-only database";
486 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
487 return "A Xapian exception occurred";
488 case NOTMUCH_STATUS_FILE_ERROR:
489 return "Something went wrong trying to read or write a file";
490 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
491 return "File is not an email";
492 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
493 return "Message ID is identical to a message in database";
494 case NOTMUCH_STATUS_NULL_POINTER:
495 return "Erroneous NULL pointer";
496 case NOTMUCH_STATUS_TAG_TOO_LONG:
497 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
498 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
499 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
500 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
501 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
502 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
503 return "Unsupported operation";
504 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
505 return "Operation requires a database upgrade";
506 case NOTMUCH_STATUS_PATH_ERROR:
507 return "Path supplied is illegal for this function";
508 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
509 return "Crypto protocol missing, malformed, or unintelligible";
510 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
511 return "Crypto engine initialization failure";
512 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
513 return "Unknown crypto protocol";
515 case NOTMUCH_STATUS_LAST_STATUS:
516 return "Unknown error status value";
521 _notmuch_database_log (notmuch_database_t *notmuch,
527 va_start (va_args, format);
529 if (notmuch->status_string)
530 talloc_free (notmuch->status_string);
532 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
537 _notmuch_database_log_append (notmuch_database_t *notmuch,
543 va_start (va_args, format);
545 if (notmuch->status_string)
546 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
548 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
554 find_doc_ids_for_term (notmuch_database_t *notmuch,
556 Xapian::PostingIterator *begin,
557 Xapian::PostingIterator *end)
559 *begin = notmuch->xapian_db->postlist_begin (term);
561 *end = notmuch->xapian_db->postlist_end (term);
565 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
566 const char *prefix_name,
568 Xapian::PostingIterator *begin,
569 Xapian::PostingIterator *end)
573 term = talloc_asprintf (notmuch, "%s%s",
574 _find_prefix (prefix_name), value);
576 find_doc_ids_for_term (notmuch, term, begin, end);
581 notmuch_private_status_t
582 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
583 const char *prefix_name,
585 unsigned int *doc_id)
587 Xapian::PostingIterator i, end;
589 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
593 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
598 #if DEBUG_DATABASE_SANITY
602 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
606 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
609 static Xapian::Document
610 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
612 return notmuch->xapian_db->get_document (doc_id);
615 /* Generate a compressed version of 'message_id' of the form:
617 * notmuch-sha1-<sha1_sum_of_message_id>
620 _notmuch_message_id_compressed (void *ctx, const char *message_id)
622 char *sha1, *compressed;
624 sha1 = _notmuch_sha1_of_string (message_id);
626 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
633 notmuch_database_find_message (notmuch_database_t *notmuch,
634 const char *message_id,
635 notmuch_message_t **message_ret)
637 notmuch_private_status_t status;
640 if (message_ret == NULL)
641 return NOTMUCH_STATUS_NULL_POINTER;
643 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
644 message_id = _notmuch_message_id_compressed (notmuch, message_id);
647 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
648 message_id, &doc_id);
650 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
653 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
655 if (*message_ret == NULL)
656 return NOTMUCH_STATUS_OUT_OF_MEMORY;
659 return NOTMUCH_STATUS_SUCCESS;
660 } catch (const Xapian::Error &error) {
661 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
662 error.get_msg ().c_str ());
663 notmuch->exception_reported = true;
665 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
670 notmuch_database_create (const char *path, notmuch_database_t **database)
672 char *status_string = NULL;
673 notmuch_status_t status;
675 status = notmuch_database_create_verbose (path, database,
679 fputs (status_string, stderr);
680 free (status_string);
687 notmuch_database_create_verbose (const char *path,
688 notmuch_database_t **database,
689 char **status_string)
691 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
692 notmuch_database_t *notmuch = NULL;
693 char *notmuch_path = NULL;
694 char *message = NULL;
699 message = strdup ("Error: Cannot create a database for a NULL path.\n");
700 status = NOTMUCH_STATUS_NULL_POINTER;
704 if (path[0] != '/') {
705 message = strdup ("Error: Database path must be absolute.\n");
706 status = NOTMUCH_STATUS_PATH_ERROR;
710 err = stat (path, &st);
712 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
713 path, strerror (errno)));
714 status = NOTMUCH_STATUS_FILE_ERROR;
718 if (! S_ISDIR (st.st_mode)) {
719 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
720 "Not a directory.\n",
722 status = NOTMUCH_STATUS_FILE_ERROR;
726 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
728 err = mkdir (notmuch_path, 0755);
731 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
732 notmuch_path, strerror (errno)));
733 status = NOTMUCH_STATUS_FILE_ERROR;
737 status = notmuch_database_open_verbose (path,
738 NOTMUCH_DATABASE_MODE_READ_WRITE,
743 /* Upgrade doesn't add these feature to existing databases, but
744 * new databases have them. */
745 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
746 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
747 notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
749 status = notmuch_database_upgrade (notmuch, NULL, NULL);
751 notmuch_database_close (notmuch);
757 talloc_free (notmuch_path);
761 *status_string = message;
768 talloc_free (notmuch);
773 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
775 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
776 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
777 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
780 return NOTMUCH_STATUS_SUCCESS;
783 /* Allocate a revision number for the next change. */
785 _notmuch_database_new_revision (notmuch_database_t *notmuch)
787 unsigned long new_revision = notmuch->revision + 1;
789 /* If we're in an atomic section, hold off on updating the
790 * committed revision number until we commit the atomic section.
792 if (notmuch->atomic_nesting)
793 notmuch->atomic_dirty = true;
795 notmuch->revision = new_revision;
800 /* Parse a database features string from the given database version.
801 * Returns the feature bit set.
803 * For version < 3, this ignores the features string and returns a
804 * hard-coded set of features.
806 * If there are unrecognized features that are required to open the
807 * database in mode (which should be 'r' or 'w'), return a
808 * comma-separated list of unrecognized but required features in
809 * *incompat_out suitable for presenting to the user. *incompat_out
810 * will be allocated from ctx.
812 static _notmuch_features
813 _parse_features (const void *ctx, const char *features, unsigned int version,
814 char mode, char **incompat_out)
816 _notmuch_features res = static_cast<_notmuch_features>(0);
817 unsigned int namelen, i;
821 /* Prior to database version 3, features were implied by the
824 return NOTMUCH_FEATURES_V0;
825 else if (version == 1)
826 return NOTMUCH_FEATURES_V1;
827 else if (version == 2)
828 return NOTMUCH_FEATURES_V2;
830 /* Parse the features string */
831 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
832 flags = strchr (features, '\t');
833 if (! flags || flags > features + llen)
835 namelen = flags - features;
837 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
838 if (strlen (feature_names[i].name) == namelen &&
839 strncmp (feature_names[i].name, features, namelen) == 0) {
840 res |= feature_names[i].value;
845 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
846 /* Unrecognized feature */
847 const char *have = strchr (flags, mode);
848 if (have && have < features + llen) {
849 /* This feature is required to access this database in
850 * 'mode', but we don't understand it. */
852 *incompat_out = talloc_strdup (ctx, "");
853 *incompat_out = talloc_asprintf_append_buffer (
854 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
864 _print_features (const void *ctx, unsigned int features)
867 char *res = talloc_strdup (ctx, "");
869 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
870 if (features & feature_names[i].value)
871 res = talloc_asprintf_append_buffer (
872 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
878 notmuch_database_open (const char *path,
879 notmuch_database_mode_t mode,
880 notmuch_database_t **database)
882 char *status_string = NULL;
883 notmuch_status_t status;
885 status = notmuch_database_open_verbose (path, mode, database,
889 fputs (status_string, stderr);
890 free (status_string);
897 notmuch_database_open_verbose (const char *path,
898 notmuch_database_mode_t mode,
899 notmuch_database_t **database,
900 char **status_string)
902 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
903 void *local = talloc_new (NULL);
904 notmuch_database_t *notmuch = NULL;
905 char *notmuch_path, *xapian_path, *incompat_features;
906 char *message = NULL;
909 unsigned int i, version;
910 static int initialized = 0;
913 message = strdup ("Error: Cannot open a database for a NULL path.\n");
914 status = NOTMUCH_STATUS_NULL_POINTER;
918 if (path[0] != '/') {
919 message = strdup ("Error: Database path must be absolute.\n");
920 status = NOTMUCH_STATUS_PATH_ERROR;
924 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
925 message = strdup ("Out of memory\n");
926 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
930 err = stat (notmuch_path, &st);
932 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
933 notmuch_path, strerror (errno)));
934 status = NOTMUCH_STATUS_FILE_ERROR;
938 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
939 message = strdup ("Out of memory\n");
940 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
944 /* Initialize the GLib type system and threads */
945 #if ! GLIB_CHECK_VERSION (2, 35, 1)
949 /* Initialize gmime */
955 notmuch = talloc_zero (NULL, notmuch_database_t);
956 notmuch->exception_reported = false;
957 notmuch->status_string = NULL;
958 notmuch->path = talloc_strdup (notmuch, path);
960 strip_trailing (notmuch->path, '/');
962 notmuch->mode = mode;
963 notmuch->atomic_nesting = 0;
966 string last_thread_id;
969 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
970 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
973 notmuch->xapian_db = new Xapian::Database (xapian_path);
976 /* Check version. As of database version 3, we represent
977 * changes in terms of features, so assume a version bump
978 * means a dramatically incompatible change. */
979 version = notmuch_database_get_version (notmuch);
980 if (version > NOTMUCH_DATABASE_VERSION) {
981 IGNORE_RESULT (asprintf (&message,
982 "Error: Notmuch database at %s\n"
983 " has a newer database format version (%u) than supported by this\n"
984 " version of notmuch (%u).\n",
985 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
986 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
987 notmuch_database_destroy (notmuch);
989 status = NOTMUCH_STATUS_FILE_ERROR;
993 /* Check features. */
994 incompat_features = NULL;
995 notmuch->features = _parse_features (
996 local, notmuch->xapian_db->get_metadata ("features").c_str (),
997 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
999 if (incompat_features) {
1000 IGNORE_RESULT (asprintf (&message,
1001 "Error: Notmuch database at %s\n"
1002 " requires features (%s)\n"
1003 " not supported by this version of notmuch.\n",
1004 notmuch_path, incompat_features));
1005 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1006 notmuch_database_destroy (notmuch);
1008 status = NOTMUCH_STATUS_FILE_ERROR;
1012 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1013 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1014 if (last_thread_id.empty ()) {
1015 notmuch->last_thread_id = 0;
1020 str = last_thread_id.c_str ();
1021 notmuch->last_thread_id = strtoull (str, &end, 16);
1023 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1026 /* Get current highest revision number. */
1027 last_mod = notmuch->xapian_db->get_value_upper_bound (
1028 NOTMUCH_VALUE_LAST_MOD);
1029 if (last_mod.empty ())
1030 notmuch->revision = 0;
1032 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1033 notmuch->uuid = talloc_strdup (
1034 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1036 notmuch->query_parser = new Xapian::QueryParser;
1037 notmuch->term_gen = new Xapian::TermGenerator;
1038 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1039 notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1040 notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP, "date:");
1041 notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1042 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1043 notmuch->query_parser->set_database (*notmuch->xapian_db);
1044 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1045 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1046 notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
1047 notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
1048 notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
1050 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1051 const prefix_t *prefix = &prefix_table[i];
1052 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1053 _setup_query_field (prefix, notmuch);
1056 status = _setup_user_query_fields (notmuch);
1057 } catch (const Xapian::Error &error) {
1058 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1059 error.get_msg ().c_str ()));
1060 notmuch_database_destroy (notmuch);
1062 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1066 talloc_free (local);
1070 *status_string = message;
1076 *database = notmuch;
1078 talloc_free (notmuch);
1083 notmuch_database_close (notmuch_database_t *notmuch)
1085 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1087 /* Many Xapian objects (and thus notmuch objects) hold references to
1088 * the database, so merely deleting the database may not suffice to
1089 * close it. Thus, we explicitly close it here. */
1090 if (notmuch->xapian_db != NULL) {
1092 /* If there's an outstanding transaction, it's unclear if
1093 * closing the Xapian database commits everything up to
1094 * that transaction, or may discard committed (but
1095 * unflushed) transactions. To be certain, explicitly
1096 * cancel any outstanding transaction before closing. */
1097 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1098 notmuch->atomic_nesting)
1099 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1100 ->cancel_transaction ();
1102 /* Close the database. This implicitly flushes
1103 * outstanding changes. */
1104 notmuch->xapian_db->close ();
1105 } catch (const Xapian::Error &error) {
1106 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1107 if (! notmuch->exception_reported) {
1108 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1109 error.get_msg ().c_str ());
1114 delete notmuch->term_gen;
1115 notmuch->term_gen = NULL;
1116 delete notmuch->query_parser;
1117 notmuch->query_parser = NULL;
1118 delete notmuch->xapian_db;
1119 notmuch->xapian_db = NULL;
1120 delete notmuch->value_range_processor;
1121 notmuch->value_range_processor = NULL;
1122 delete notmuch->date_range_processor;
1123 notmuch->date_range_processor = NULL;
1124 delete notmuch->last_mod_range_processor;
1125 notmuch->last_mod_range_processor = NULL;
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);
1339 talloc_free (notmuch);
1345 notmuch_database_get_path (notmuch_database_t *notmuch)
1347 return notmuch->path;
1351 notmuch_database_get_version (notmuch_database_t *notmuch)
1353 unsigned int version;
1354 string version_string;
1358 version_string = notmuch->xapian_db->get_metadata ("version");
1359 if (version_string.empty ())
1362 str = version_string.c_str ();
1363 if (str == NULL || *str == '\0')
1366 version = strtoul (str, &end, 10);
1368 INTERNAL_ERROR ("Malformed database version: %s", str);
1374 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1376 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1377 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1378 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1381 static volatile sig_atomic_t do_progress_notify = 0;
1384 handle_sigalrm (unused (int signal))
1386 do_progress_notify = 1;
1389 /* Upgrade the current database.
1391 * After opening a database in read-write mode, the client should
1392 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1393 * if so, upgrade with this function before making any modifications.
1395 * The optional progress_notify callback can be used by the caller to
1396 * provide progress indication to the user. If non-NULL it will be
1397 * called periodically with 'count' as the number of messages upgraded
1398 * so far and 'total' the overall number of messages that will be
1402 notmuch_database_upgrade (notmuch_database_t *notmuch,
1403 void (*progress_notify) (void *closure,
1407 void *local = talloc_new (NULL);
1408 Xapian::TermIterator t, t_end;
1409 Xapian::WritableDatabase *db;
1410 struct sigaction action;
1411 struct itimerval timerval;
1412 bool timer_is_active = false;
1413 enum _notmuch_features target_features, new_features;
1414 notmuch_status_t status;
1415 notmuch_private_status_t private_status;
1416 notmuch_query_t *query = NULL;
1417 unsigned int count = 0, total = 0;
1419 status = _notmuch_database_ensure_writable (notmuch);
1423 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1425 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1426 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1428 if (! notmuch_database_needs_upgrade (notmuch))
1429 return NOTMUCH_STATUS_SUCCESS;
1431 if (progress_notify) {
1432 /* Set up our handler for SIGALRM */
1433 memset (&action, 0, sizeof (struct sigaction));
1434 action.sa_handler = handle_sigalrm;
1435 sigemptyset (&action.sa_mask);
1436 action.sa_flags = SA_RESTART;
1437 sigaction (SIGALRM, &action, NULL);
1439 /* Then start a timer to send SIGALRM once per second. */
1440 timerval.it_interval.tv_sec = 1;
1441 timerval.it_interval.tv_usec = 0;
1442 timerval.it_value.tv_sec = 1;
1443 timerval.it_value.tv_usec = 0;
1444 setitimer (ITIMER_REAL, &timerval, NULL);
1446 timer_is_active = true;
1449 /* Figure out how much total work we need to do. */
1451 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1452 NOTMUCH_FEATURE_LAST_MOD)) {
1453 query = notmuch_query_create (notmuch, "");
1456 status = notmuch_query_count_messages (query, &msg_count);
1461 notmuch_query_destroy (query);
1464 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1465 t_end = db->allterms_end ("XTIMESTAMP");
1466 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1469 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1470 /* The ghost message upgrade converts all thread_id_*
1471 * metadata values into ghost message documents. */
1472 t_end = db->metadata_keys_end ("thread_id_");
1473 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1477 /* Perform the upgrade in a transaction. */
1478 db->begin_transaction (true);
1480 /* Set the target features so we write out changes in the desired
1482 notmuch->features = target_features;
1484 /* Perform per-message upgrades. */
1486 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1487 NOTMUCH_FEATURE_LAST_MOD)) {
1488 notmuch_messages_t *messages;
1489 notmuch_message_t *message;
1492 query = notmuch_query_create (notmuch, "");
1494 status = notmuch_query_search_messages (query, &messages);
1498 notmuch_messages_valid (messages);
1499 notmuch_messages_move_to_next (messages)) {
1500 if (do_progress_notify) {
1501 progress_notify (closure, (double) count / total);
1502 do_progress_notify = 0;
1505 message = notmuch_messages_get (messages);
1507 /* Before version 1, each message document had its
1508 * filename in the data field. Copy that into the new
1509 * format by calling notmuch_message_add_filename.
1511 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1512 filename = _notmuch_message_talloc_copy_data (message);
1513 if (filename && *filename != '\0') {
1514 _notmuch_message_add_filename (message, filename);
1515 _notmuch_message_clear_data (message);
1517 talloc_free (filename);
1520 /* Prior to version 2, the "folder:" prefix was
1521 * probabilistic and stemmed. Change it to the current
1522 * boolean prefix. Add "path:" prefixes while at it.
1524 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1525 _notmuch_message_upgrade_folder (message);
1527 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1528 * track modification revisions. Give all messages the
1529 * next available revision; since we just started tracking
1530 * revisions for this database, that will be 1.
1532 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1533 _notmuch_message_upgrade_last_mod (message);
1535 _notmuch_message_sync (message);
1537 notmuch_message_destroy (message);
1542 notmuch_query_destroy (query);
1546 /* Perform per-directory upgrades. */
1548 /* Before version 1 we stored directory timestamps in
1549 * XTIMESTAMP documents instead of the current XDIRECTORY
1550 * documents. So copy those as well. */
1551 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1552 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1554 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1557 Xapian::PostingIterator p, p_end;
1558 std::string term = *t;
1560 p_end = notmuch->xapian_db->postlist_end (term);
1562 for (p = notmuch->xapian_db->postlist_begin (term);
1565 Xapian::Document document;
1567 notmuch_directory_t *directory;
1569 if (do_progress_notify) {
1570 progress_notify (closure, (double) count / total);
1571 do_progress_notify = 0;
1574 document = find_document_for_doc_id (notmuch, *p);
1575 mtime = Xapian::sortable_unserialise (
1576 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1578 directory = _notmuch_directory_create (notmuch, term.c_str () + 10,
1579 NOTMUCH_FIND_CREATE, &status);
1580 notmuch_directory_set_mtime (directory, mtime);
1581 notmuch_directory_destroy (directory);
1583 db->delete_document (*p);
1590 /* Perform metadata upgrades. */
1592 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1593 * messages were stored as database metadata. Change these to
1596 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1597 notmuch_message_t *message;
1598 std::string message_id, thread_id;
1600 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1601 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1603 if (do_progress_notify) {
1604 progress_notify (closure, (double) count / total);
1605 do_progress_notify = 0;
1608 message_id = (*t).substr (
1609 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1610 thread_id = db->get_metadata (*t);
1612 /* Create ghost message */
1613 message = _notmuch_message_create_for_message_id (
1614 notmuch, message_id.c_str (), &private_status);
1615 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1616 /* Document already exists; ignore the stored thread ID */
1617 } else if (private_status ==
1618 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1619 private_status = _notmuch_message_initialize_ghost (
1620 message, thread_id.c_str ());
1621 if (! private_status)
1622 _notmuch_message_sync (message);
1625 if (private_status) {
1626 _notmuch_database_log (notmuch,
1627 "Upgrade failed while creating ghost messages.\n");
1628 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1632 /* Clear saved metadata thread ID */
1633 db->set_metadata (*t, "");
1639 status = NOTMUCH_STATUS_SUCCESS;
1640 db->set_metadata ("features", _print_features (local, notmuch->features));
1641 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1644 if (status == NOTMUCH_STATUS_SUCCESS)
1645 db->commit_transaction ();
1647 db->cancel_transaction ();
1649 if (timer_is_active) {
1650 /* Now stop the timer. */
1651 timerval.it_interval.tv_sec = 0;
1652 timerval.it_interval.tv_usec = 0;
1653 timerval.it_value.tv_sec = 0;
1654 timerval.it_value.tv_usec = 0;
1655 setitimer (ITIMER_REAL, &timerval, NULL);
1657 /* And disable the signal handler. */
1658 action.sa_handler = SIG_IGN;
1659 sigaction (SIGALRM, &action, NULL);
1663 notmuch_query_destroy (query);
1665 talloc_free (local);
1670 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1672 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1673 notmuch->atomic_nesting > 0)
1676 if (notmuch_database_needs_upgrade (notmuch))
1677 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1680 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1681 } catch (const Xapian::Error &error) {
1682 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1683 error.get_msg ().c_str ());
1684 notmuch->exception_reported = true;
1685 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1689 notmuch->atomic_nesting++;
1690 return NOTMUCH_STATUS_SUCCESS;
1694 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1696 Xapian::WritableDatabase *db;
1698 if (notmuch->atomic_nesting == 0)
1699 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1701 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1702 notmuch->atomic_nesting > 1)
1705 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1707 db->commit_transaction ();
1709 /* This is a hack for testing. Xapian never flushes on a
1710 * non-flushed commit, even if the flush threshold is 1.
1711 * However, we rely on flushing to test atomicity. */
1712 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1713 if (thresh && atoi (thresh) == 1)
1715 } catch (const Xapian::Error &error) {
1716 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1717 error.get_msg ().c_str ());
1718 notmuch->exception_reported = true;
1719 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1722 if (notmuch->atomic_dirty) {
1723 ++notmuch->revision;
1724 notmuch->atomic_dirty = false;
1728 notmuch->atomic_nesting--;
1729 return NOTMUCH_STATUS_SUCCESS;
1733 notmuch_database_get_revision (notmuch_database_t *notmuch,
1737 *uuid = notmuch->uuid;
1738 return notmuch->revision;
1741 /* We allow the user to use arbitrarily long paths for directories. But
1742 * we have a term-length limit. So if we exceed that, we'll use the
1743 * SHA-1 of the path for the database term.
1745 * Note: This function may return the original value of 'path'. If it
1746 * does not, then the caller is responsible to free() the returned
1750 _notmuch_database_get_directory_db_path (const char *path)
1752 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1754 if (term_len > NOTMUCH_TERM_MAX)
1755 return _notmuch_sha1_of_string (path);
1760 /* Given a path, split it into two parts: the directory part is all
1761 * components except for the last, and the basename is that last
1762 * component. Getting the return-value for either part is optional
1763 * (the caller can pass NULL).
1765 * The original 'path' can represent either a regular file or a
1766 * directory---the splitting will be carried out in the same way in
1767 * either case. Trailing slashes on 'path' will be ignored, and any
1768 * cases of multiple '/' characters appearing in series will be
1769 * treated as a single '/'.
1771 * Allocation (if any) will have 'ctx' as the talloc owner. But
1772 * pointers will be returned within the original path string whenever
1775 * Note: If 'path' is non-empty and contains no non-trailing slash,
1776 * (that is, consists of a filename with no parent directory), then
1777 * the directory returned will be an empty string. However, if 'path'
1778 * is an empty string, then both directory and basename will be
1782 _notmuch_database_split_path (void *ctx,
1784 const char **directory,
1785 const char **basename)
1789 if (path == NULL || *path == '\0') {
1794 return NOTMUCH_STATUS_SUCCESS;
1797 /* Find the last slash (not counting a trailing slash), if any. */
1799 slash = path + strlen (path) - 1;
1801 /* First, skip trailing slashes. */
1802 while (slash != path && *slash == '/')
1805 /* Then, find a slash. */
1806 while (slash != path && *slash != '/') {
1813 /* Finally, skip multiple slashes. */
1814 while (slash != path && *(slash - 1) == '/')
1817 if (slash == path) {
1819 *directory = talloc_strdup (ctx, "");
1824 *directory = talloc_strndup (ctx, path, slash - path);
1827 return NOTMUCH_STATUS_SUCCESS;
1830 /* Find the document ID of the specified directory.
1832 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1833 * created if one does not exist for 'path'. Otherwise, if the
1834 * directory document does not exist, this sets *directory_id to
1835 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1838 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1840 notmuch_find_flags_t flags,
1841 unsigned int *directory_id)
1843 notmuch_directory_t *directory;
1844 notmuch_status_t status;
1848 return NOTMUCH_STATUS_SUCCESS;
1851 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1852 if (status || ! directory) {
1857 *directory_id = _notmuch_directory_get_document_id (directory);
1859 notmuch_directory_destroy (directory);
1861 return NOTMUCH_STATUS_SUCCESS;
1865 _notmuch_database_get_directory_path (void *ctx,
1866 notmuch_database_t *notmuch,
1867 unsigned int doc_id)
1869 Xapian::Document document;
1871 document = find_document_for_doc_id (notmuch, doc_id);
1873 return talloc_strdup (ctx, document.get_data ().c_str ());
1876 /* Given a legal 'filename' for the database, (either relative to
1877 * database path or absolute with initial components identical to
1878 * database path), return a new string (with 'ctx' as the talloc
1879 * owner) suitable for use as a direntry term value.
1881 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1882 * will be created in the database as needed. Otherwise, if the
1883 * necessary directory documents do not exist, this sets
1884 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1887 _notmuch_database_filename_to_direntry (void *ctx,
1888 notmuch_database_t *notmuch,
1889 const char *filename,
1890 notmuch_find_flags_t flags,
1893 const char *relative, *directory, *basename;
1894 Xapian::docid directory_id;
1895 notmuch_status_t status;
1897 relative = _notmuch_database_relative_path (notmuch, filename);
1899 status = _notmuch_database_split_path (ctx, relative,
1900 &directory, &basename);
1904 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1906 if (status || directory_id == (unsigned int) -1) {
1911 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1913 return NOTMUCH_STATUS_SUCCESS;
1916 /* Given a legal 'path' for the database, return the relative path.
1918 * The return value will be a pointer to the original path contents,
1919 * and will be either the original string (if 'path' was relative) or
1920 * a portion of the string (if path was absolute and begins with the
1924 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1927 const char *db_path, *relative;
1928 unsigned int db_path_len;
1930 db_path = notmuch_database_get_path (notmuch);
1931 db_path_len = strlen (db_path);
1935 if (*relative == '/') {
1936 while (*relative == '/' && *(relative + 1) == '/')
1939 if (strncmp (relative, db_path, db_path_len) == 0) {
1940 relative += db_path_len;
1941 while (*relative == '/')
1950 notmuch_database_get_directory (notmuch_database_t *notmuch,
1952 notmuch_directory_t **directory)
1954 notmuch_status_t status;
1956 if (directory == NULL)
1957 return NOTMUCH_STATUS_NULL_POINTER;
1961 *directory = _notmuch_directory_create (notmuch, path,
1962 NOTMUCH_FIND_LOOKUP, &status);
1963 } catch (const Xapian::Error &error) {
1964 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1965 error.get_msg ().c_str ());
1966 notmuch->exception_reported = true;
1967 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1972 /* Allocate a document ID that satisfies the following criteria:
1974 * 1. The ID does not exist for any document in the Xapian database
1976 * 2. The ID was not previously returned from this function
1978 * 3. The ID is the smallest integer satisfying (1) and (2)
1980 * This function will trigger an internal error if these constraints
1981 * cannot all be satisfied, (that is, the pool of available document
1982 * IDs has been exhausted).
1985 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1987 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1989 notmuch->last_doc_id++;
1991 if (notmuch->last_doc_id == 0)
1992 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1994 return notmuch->last_doc_id;
1998 notmuch_database_remove_message (notmuch_database_t *notmuch,
1999 const char *filename)
2001 notmuch_status_t status;
2002 notmuch_message_t *message;
2004 status = notmuch_database_find_message_by_filename (notmuch, filename,
2007 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2008 status = _notmuch_message_remove_filename (message, filename);
2009 if (status == NOTMUCH_STATUS_SUCCESS)
2010 _notmuch_message_delete (message);
2011 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2012 _notmuch_message_sync (message);
2014 notmuch_message_destroy (message);
2021 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2022 const char *filename,
2023 notmuch_message_t **message_ret)
2026 const char *prefix = _find_prefix ("file-direntry");
2027 char *direntry, *term;
2028 Xapian::PostingIterator i, end;
2029 notmuch_status_t status;
2031 if (message_ret == NULL)
2032 return NOTMUCH_STATUS_NULL_POINTER;
2034 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2035 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2037 /* return NULL on any failure */
2038 *message_ret = NULL;
2040 local = talloc_new (notmuch);
2043 status = _notmuch_database_filename_to_direntry (
2044 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2045 if (status || ! direntry)
2048 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2050 find_doc_ids_for_term (notmuch, term, &i, &end);
2053 notmuch_private_status_t private_status;
2055 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2057 if (*message_ret == NULL)
2058 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2060 } catch (const Xapian::Error &error) {
2061 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2062 error.get_msg ().c_str ());
2063 notmuch->exception_reported = true;
2064 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2068 talloc_free (local);
2070 if (status && *message_ret) {
2071 notmuch_message_destroy (*message_ret);
2072 *message_ret = NULL;
2077 notmuch_string_list_t *
2078 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2079 Xapian::TermIterator &end,
2082 int prefix_len = strlen (prefix);
2083 notmuch_string_list_t *list;
2085 list = _notmuch_string_list_create (ctx);
2086 if (unlikely (list == NULL))
2089 for (i.skip_to (prefix); i != end; i++) {
2090 /* Terminate loop at first term without desired prefix. */
2091 if (strncmp ((*i).c_str (), prefix, prefix_len))
2094 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2101 notmuch_database_get_all_tags (notmuch_database_t *db)
2103 Xapian::TermIterator i, end;
2104 notmuch_string_list_t *tags;
2107 i = db->xapian_db->allterms_begin ();
2108 end = db->xapian_db->allterms_end ();
2109 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2110 _find_prefix ("tag"));
2111 _notmuch_string_list_sort (tags);
2112 return _notmuch_tags_create (db, tags);
2113 } catch (const Xapian::Error &error) {
2114 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2115 error.get_msg ().c_str ());
2116 db->exception_reported = true;
2122 notmuch_database_status_string (const notmuch_database_t *notmuch)
2124 return notmuch->status_string;