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 #if HAVE_XAPIAN_FIELD_PROCESSOR
295 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
296 NOTMUCH_FIELD_PROCESSOR },
297 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
298 NOTMUCH_FIELD_PROCESSOR },
300 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
301 NOTMUCH_FIELD_PROBABILISTIC |
302 NOTMUCH_FIELD_PROCESSOR },
303 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
304 NOTMUCH_FIELD_PROBABILISTIC },
305 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
306 NOTMUCH_FIELD_PROBABILISTIC },
307 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
308 NOTMUCH_FIELD_PROBABILISTIC },
309 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
310 NOTMUCH_FIELD_PROBABILISTIC |
311 NOTMUCH_FIELD_PROCESSOR},
315 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
318 notmuch->query_parser->add_prefix ("",prefix->prefix);
319 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
320 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
322 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
326 _user_prefix (void *ctx, const char* name)
328 return talloc_asprintf(ctx, "XU%s:", name);
331 static notmuch_status_t
332 _setup_user_query_fields (notmuch_database_t *notmuch)
334 notmuch_config_list_t *list;
335 notmuch_status_t status;
337 status = notmuch_database_get_config_list (notmuch, CONFIG_HEADER_PREFIX, &list);
341 for (; notmuch_config_list_valid (list); notmuch_config_list_move_to_next (list)) {
343 prefix_t query_field;
345 const char *key = notmuch_config_list_key (list)
346 + sizeof (CONFIG_HEADER_PREFIX) - 1;
348 query_field.name = talloc_strdup (notmuch, key);
349 query_field.prefix = _user_prefix (notmuch, key);
350 query_field.flags = NOTMUCH_FIELD_PROBABILISTIC
351 | NOTMUCH_FIELD_EXTERNAL;
353 _setup_query_field_default (&query_field, notmuch);
356 notmuch_config_list_destroy (list);
358 return NOTMUCH_STATUS_SUCCESS;
361 #if HAVE_XAPIAN_FIELD_PROCESSOR
363 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
365 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
366 Xapian::FieldProcessor *fp;
368 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
369 fp = (new DateFieldProcessor())->release ();
370 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
371 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
372 else if (STRNCMP_LITERAL(prefix->name, "thread") == 0)
373 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
375 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
376 *notmuch->query_parser, notmuch))->release ();
378 /* we treat all field-processor fields as boolean in order to get the raw input */
380 notmuch->query_parser->add_prefix ("",prefix->prefix);
381 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
383 _setup_query_field_default (prefix, notmuch);
388 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
390 _setup_query_field_default (prefix, notmuch);
395 _find_prefix (const char *name)
399 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
400 if (strcmp (name, prefix_table[i].name) == 0)
401 return prefix_table[i].prefix;
404 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
409 static const struct {
410 /* NOTMUCH_FEATURE_* value. */
411 _notmuch_features value;
412 /* Feature name as it appears in the database. This name should
413 * be appropriate for displaying to the user if an older version
414 * of notmuch doesn't support this feature. */
416 /* Compatibility flags when this feature is declared. */
418 } feature_names[] = {
419 { NOTMUCH_FEATURE_FILE_TERMS,
420 "multiple paths per message", "rw" },
421 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
422 "relative directory paths", "rw" },
423 /* Header values are not required for reading a database because a
424 * reader can just refer to the message file. */
425 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
426 "from/subject/message-ID in database", "w" },
427 { NOTMUCH_FEATURE_BOOL_FOLDER,
428 "exact folder:/path: search", "rw" },
429 { NOTMUCH_FEATURE_GHOSTS,
430 "mail documents for missing messages", "w"},
431 /* Knowledge of the index mime-types are not required for reading
432 * a database because a reader will just be unable to query
434 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
435 "indexed MIME types", "w"},
436 { NOTMUCH_FEATURE_LAST_MOD,
437 "modification tracking", "w"},
438 /* Existing databases will work fine for all queries not involving
440 { NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY,
441 "index body and headers separately", "w"},
445 notmuch_status_to_string (notmuch_status_t status)
448 case NOTMUCH_STATUS_SUCCESS:
449 return "No error occurred";
450 case NOTMUCH_STATUS_OUT_OF_MEMORY:
451 return "Out of memory";
452 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
453 return "Attempt to write to a read-only database";
454 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
455 return "A Xapian exception occurred";
456 case NOTMUCH_STATUS_FILE_ERROR:
457 return "Something went wrong trying to read or write a file";
458 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
459 return "File is not an email";
460 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
461 return "Message ID is identical to a message in database";
462 case NOTMUCH_STATUS_NULL_POINTER:
463 return "Erroneous NULL pointer";
464 case NOTMUCH_STATUS_TAG_TOO_LONG:
465 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
466 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
467 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
468 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
469 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
470 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
471 return "Unsupported operation";
472 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
473 return "Operation requires a database upgrade";
474 case NOTMUCH_STATUS_PATH_ERROR:
475 return "Path supplied is illegal for this function";
476 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
477 return "Crypto protocol missing, malformed, or unintelligible";
478 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
479 return "Crypto engine initialization failure";
480 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
481 return "Unknown crypto protocol";
483 case NOTMUCH_STATUS_LAST_STATUS:
484 return "Unknown error status value";
489 _notmuch_database_log (notmuch_database_t *notmuch,
495 va_start (va_args, format);
497 if (notmuch->status_string)
498 talloc_free (notmuch->status_string);
500 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
505 _notmuch_database_log_append (notmuch_database_t *notmuch,
511 va_start (va_args, format);
513 if (notmuch->status_string)
514 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
516 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
522 find_doc_ids_for_term (notmuch_database_t *notmuch,
524 Xapian::PostingIterator *begin,
525 Xapian::PostingIterator *end)
527 *begin = notmuch->xapian_db->postlist_begin (term);
529 *end = notmuch->xapian_db->postlist_end (term);
533 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
534 const char *prefix_name,
536 Xapian::PostingIterator *begin,
537 Xapian::PostingIterator *end)
541 term = talloc_asprintf (notmuch, "%s%s",
542 _find_prefix (prefix_name), value);
544 find_doc_ids_for_term (notmuch, term, begin, end);
549 notmuch_private_status_t
550 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
551 const char *prefix_name,
553 unsigned int *doc_id)
555 Xapian::PostingIterator i, end;
557 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
561 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
566 #if DEBUG_DATABASE_SANITY
570 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
574 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
577 static Xapian::Document
578 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
580 return notmuch->xapian_db->get_document (doc_id);
583 /* Generate a compressed version of 'message_id' of the form:
585 * notmuch-sha1-<sha1_sum_of_message_id>
588 _notmuch_message_id_compressed (void *ctx, const char *message_id)
590 char *sha1, *compressed;
592 sha1 = _notmuch_sha1_of_string (message_id);
594 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
601 notmuch_database_find_message (notmuch_database_t *notmuch,
602 const char *message_id,
603 notmuch_message_t **message_ret)
605 notmuch_private_status_t status;
608 if (message_ret == NULL)
609 return NOTMUCH_STATUS_NULL_POINTER;
611 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
612 message_id = _notmuch_message_id_compressed (notmuch, message_id);
615 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
616 message_id, &doc_id);
618 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
621 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
623 if (*message_ret == NULL)
624 return NOTMUCH_STATUS_OUT_OF_MEMORY;
627 return NOTMUCH_STATUS_SUCCESS;
628 } catch (const Xapian::Error &error) {
629 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
630 error.get_msg().c_str());
631 notmuch->exception_reported = true;
633 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
638 notmuch_database_create (const char *path, notmuch_database_t **database)
640 char *status_string = NULL;
641 notmuch_status_t status;
643 status = notmuch_database_create_verbose (path, database,
647 fputs (status_string, stderr);
648 free (status_string);
655 notmuch_database_create_verbose (const char *path,
656 notmuch_database_t **database,
657 char **status_string)
659 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
660 notmuch_database_t *notmuch = NULL;
661 char *notmuch_path = NULL;
662 char *message = NULL;
667 message = strdup ("Error: Cannot create a database for a NULL path.\n");
668 status = NOTMUCH_STATUS_NULL_POINTER;
672 if (path[0] != '/') {
673 message = strdup ("Error: Database path must be absolute.\n");
674 status = NOTMUCH_STATUS_PATH_ERROR;
678 err = stat (path, &st);
680 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
681 path, strerror (errno)));
682 status = NOTMUCH_STATUS_FILE_ERROR;
686 if (! S_ISDIR (st.st_mode)) {
687 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
688 "Not a directory.\n",
690 status = NOTMUCH_STATUS_FILE_ERROR;
694 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
696 err = mkdir (notmuch_path, 0755);
699 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
700 notmuch_path, strerror (errno)));
701 status = NOTMUCH_STATUS_FILE_ERROR;
705 status = notmuch_database_open_verbose (path,
706 NOTMUCH_DATABASE_MODE_READ_WRITE,
711 /* Upgrade doesn't add these feature to existing databases, but
712 * new databases have them. */
713 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
714 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
715 notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
717 status = notmuch_database_upgrade (notmuch, NULL, NULL);
719 notmuch_database_close(notmuch);
725 talloc_free (notmuch_path);
729 *status_string = message;
736 talloc_free (notmuch);
741 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
743 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
744 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
745 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
748 return NOTMUCH_STATUS_SUCCESS;
751 /* Allocate a revision number for the next change. */
753 _notmuch_database_new_revision (notmuch_database_t *notmuch)
755 unsigned long new_revision = notmuch->revision + 1;
757 /* If we're in an atomic section, hold off on updating the
758 * committed revision number until we commit the atomic section.
760 if (notmuch->atomic_nesting)
761 notmuch->atomic_dirty = true;
763 notmuch->revision = new_revision;
768 /* Parse a database features string from the given database version.
769 * Returns the feature bit set.
771 * For version < 3, this ignores the features string and returns a
772 * hard-coded set of features.
774 * If there are unrecognized features that are required to open the
775 * database in mode (which should be 'r' or 'w'), return a
776 * comma-separated list of unrecognized but required features in
777 * *incompat_out suitable for presenting to the user. *incompat_out
778 * will be allocated from ctx.
780 static _notmuch_features
781 _parse_features (const void *ctx, const char *features, unsigned int version,
782 char mode, char **incompat_out)
784 _notmuch_features res = static_cast<_notmuch_features>(0);
785 unsigned int namelen, i;
789 /* Prior to database version 3, features were implied by the
792 return NOTMUCH_FEATURES_V0;
793 else if (version == 1)
794 return NOTMUCH_FEATURES_V1;
795 else if (version == 2)
796 return NOTMUCH_FEATURES_V2;
798 /* Parse the features string */
799 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
800 flags = strchr (features, '\t');
801 if (! flags || flags > features + llen)
803 namelen = flags - features;
805 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
806 if (strlen (feature_names[i].name) == namelen &&
807 strncmp (feature_names[i].name, features, namelen) == 0) {
808 res |= feature_names[i].value;
813 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
814 /* Unrecognized feature */
815 const char *have = strchr (flags, mode);
816 if (have && have < features + llen) {
817 /* This feature is required to access this database in
818 * 'mode', but we don't understand it. */
820 *incompat_out = talloc_strdup (ctx, "");
821 *incompat_out = talloc_asprintf_append_buffer (
822 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
832 _print_features (const void *ctx, unsigned int features)
835 char *res = talloc_strdup (ctx, "");
837 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
838 if (features & feature_names[i].value)
839 res = talloc_asprintf_append_buffer (
840 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
846 notmuch_database_open (const char *path,
847 notmuch_database_mode_t mode,
848 notmuch_database_t **database)
850 char *status_string = NULL;
851 notmuch_status_t status;
853 status = notmuch_database_open_verbose (path, mode, database,
857 fputs (status_string, stderr);
858 free (status_string);
865 notmuch_database_open_verbose (const char *path,
866 notmuch_database_mode_t mode,
867 notmuch_database_t **database,
868 char **status_string)
870 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
871 void *local = talloc_new (NULL);
872 notmuch_database_t *notmuch = NULL;
873 char *notmuch_path, *xapian_path, *incompat_features;
874 char *message = NULL;
877 unsigned int i, version;
878 static int initialized = 0;
881 message = strdup ("Error: Cannot open a database for a NULL path.\n");
882 status = NOTMUCH_STATUS_NULL_POINTER;
886 if (path[0] != '/') {
887 message = strdup ("Error: Database path must be absolute.\n");
888 status = NOTMUCH_STATUS_PATH_ERROR;
892 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
893 message = strdup ("Out of memory\n");
894 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
898 err = stat (notmuch_path, &st);
900 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
901 notmuch_path, strerror (errno)));
902 status = NOTMUCH_STATUS_FILE_ERROR;
906 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
907 message = strdup ("Out of memory\n");
908 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
912 /* Initialize the GLib type system and threads */
913 #if !GLIB_CHECK_VERSION(2, 35, 1)
917 /* Initialize gmime */
923 notmuch = talloc_zero (NULL, notmuch_database_t);
924 notmuch->exception_reported = false;
925 notmuch->status_string = NULL;
926 notmuch->path = talloc_strdup (notmuch, path);
928 strip_trailing(notmuch->path, '/');
930 notmuch->mode = mode;
931 notmuch->atomic_nesting = 0;
934 string last_thread_id;
937 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
938 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
941 notmuch->xapian_db = new Xapian::Database (xapian_path);
944 /* Check version. As of database version 3, we represent
945 * changes in terms of features, so assume a version bump
946 * means a dramatically incompatible change. */
947 version = notmuch_database_get_version (notmuch);
948 if (version > NOTMUCH_DATABASE_VERSION) {
949 IGNORE_RESULT (asprintf (&message,
950 "Error: Notmuch database at %s\n"
951 " has a newer database format version (%u) than supported by this\n"
952 " version of notmuch (%u).\n",
953 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
954 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
955 notmuch_database_destroy (notmuch);
957 status = NOTMUCH_STATUS_FILE_ERROR;
961 /* Check features. */
962 incompat_features = NULL;
963 notmuch->features = _parse_features (
964 local, notmuch->xapian_db->get_metadata ("features").c_str (),
965 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
967 if (incompat_features) {
968 IGNORE_RESULT (asprintf (&message,
969 "Error: Notmuch database at %s\n"
970 " requires features (%s)\n"
971 " not supported by this version of notmuch.\n",
972 notmuch_path, incompat_features));
973 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
974 notmuch_database_destroy (notmuch);
976 status = NOTMUCH_STATUS_FILE_ERROR;
980 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
981 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
982 if (last_thread_id.empty ()) {
983 notmuch->last_thread_id = 0;
988 str = last_thread_id.c_str ();
989 notmuch->last_thread_id = strtoull (str, &end, 16);
991 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
994 /* Get current highest revision number. */
995 last_mod = notmuch->xapian_db->get_value_upper_bound (
996 NOTMUCH_VALUE_LAST_MOD);
997 if (last_mod.empty ())
998 notmuch->revision = 0;
1000 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1001 notmuch->uuid = talloc_strdup (
1002 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1004 notmuch->query_parser = new Xapian::QueryParser;
1005 notmuch->term_gen = new Xapian::TermGenerator;
1006 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1007 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1008 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1009 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1011 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1012 notmuch->query_parser->set_database (*notmuch->xapian_db);
1013 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1014 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1015 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1016 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1017 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1019 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1020 const prefix_t *prefix = &prefix_table[i];
1021 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1022 _setup_query_field (prefix, notmuch);
1025 status = _setup_user_query_fields (notmuch);
1026 } catch (const Xapian::Error &error) {
1027 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1028 error.get_msg().c_str()));
1029 notmuch_database_destroy (notmuch);
1031 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1035 talloc_free (local);
1039 *status_string = message;
1045 *database = notmuch;
1047 talloc_free (notmuch);
1052 notmuch_database_close (notmuch_database_t *notmuch)
1054 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1056 /* Many Xapian objects (and thus notmuch objects) hold references to
1057 * the database, so merely deleting the database may not suffice to
1058 * close it. Thus, we explicitly close it here. */
1059 if (notmuch->xapian_db != NULL) {
1061 /* If there's an outstanding transaction, it's unclear if
1062 * closing the Xapian database commits everything up to
1063 * that transaction, or may discard committed (but
1064 * unflushed) transactions. To be certain, explicitly
1065 * cancel any outstanding transaction before closing. */
1066 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1067 notmuch->atomic_nesting)
1068 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1069 ->cancel_transaction ();
1071 /* Close the database. This implicitly flushes
1072 * outstanding changes. */
1073 notmuch->xapian_db->close();
1074 } catch (const Xapian::Error &error) {
1075 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1076 if (! notmuch->exception_reported) {
1077 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1078 error.get_msg().c_str());
1083 delete notmuch->term_gen;
1084 notmuch->term_gen = NULL;
1085 delete notmuch->query_parser;
1086 notmuch->query_parser = NULL;
1087 delete notmuch->xapian_db;
1088 notmuch->xapian_db = NULL;
1089 delete notmuch->value_range_processor;
1090 notmuch->value_range_processor = NULL;
1091 delete notmuch->date_range_processor;
1092 notmuch->date_range_processor = NULL;
1093 delete notmuch->last_mod_range_processor;
1094 notmuch->last_mod_range_processor = NULL;
1100 _notmuch_database_reopen (notmuch_database_t *notmuch)
1102 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1103 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1106 notmuch->xapian_db->reopen ();
1107 } catch (const Xapian::Error &error) {
1108 if (! notmuch->exception_reported) {
1109 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1110 error.get_msg ().c_str ());
1111 notmuch->exception_reported = true;
1113 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1118 return NOTMUCH_STATUS_SUCCESS;
1122 unlink_cb (const char *path,
1123 unused (const struct stat *sb),
1125 unused (struct FTW *ftw))
1127 return remove (path);
1131 rmtree (const char *path)
1133 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1136 class NotmuchCompactor : public Xapian::Compactor
1138 notmuch_compact_status_cb_t status_cb;
1139 void *status_closure;
1142 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1143 status_cb (cb), status_closure (closure) { }
1146 set_status (const std::string &table, const std::string &status)
1150 if (status_cb == NULL)
1153 if (status.length () == 0)
1154 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1156 msg = talloc_asprintf (NULL, " %s", status.c_str());
1162 status_cb (msg, status_closure);
1167 /* Compacts the given database, optionally saving the original database
1168 * in backup_path. Additionally, a callback function can be provided to
1169 * give the user feedback on the progress of the (likely long-lived)
1170 * compaction process.
1172 * The backup path must point to a directory on the same volume as the
1173 * original database. Passing a NULL backup_path will result in the
1174 * uncompacted database being deleted after compaction has finished.
1175 * Note that the database write lock will be held during the
1176 * compaction process to protect data integrity.
1179 notmuch_database_compact (const char *path,
1180 const char *backup_path,
1181 notmuch_compact_status_cb_t status_cb,
1185 char *notmuch_path, *xapian_path, *compact_xapian_path;
1186 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1187 notmuch_database_t *notmuch = NULL;
1188 struct stat statbuf;
1190 char *message = NULL;
1192 local = talloc_new (NULL);
1194 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1196 ret = notmuch_database_open_verbose (path,
1197 NOTMUCH_DATABASE_MODE_READ_WRITE,
1201 if (status_cb) status_cb (message, closure);
1205 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1206 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1210 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1211 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1215 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1216 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1220 if (backup_path == NULL) {
1221 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1222 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1225 keep_backup = false;
1231 if (stat (backup_path, &statbuf) != -1) {
1232 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1233 ret = NOTMUCH_STATUS_FILE_ERROR;
1236 if (errno != ENOENT) {
1237 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1239 ret = NOTMUCH_STATUS_FILE_ERROR;
1243 /* Unconditionally attempt to remove old work-in-progress database (if
1244 * any). This is "protected" by database lock. If this fails due to write
1245 * errors (etc), the following code will fail and provide error message.
1247 (void) rmtree (compact_xapian_path);
1250 NotmuchCompactor compactor (status_cb, closure);
1252 compactor.set_renumber (false);
1253 compactor.add_source (xapian_path);
1254 compactor.set_destdir (compact_xapian_path);
1255 compactor.compact ();
1256 } catch (const Xapian::Error &error) {
1257 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1258 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1262 if (rename (xapian_path, backup_path)) {
1263 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1264 xapian_path, backup_path, strerror (errno));
1265 ret = NOTMUCH_STATUS_FILE_ERROR;
1269 if (rename (compact_xapian_path, xapian_path)) {
1270 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1271 compact_xapian_path, xapian_path, strerror (errno));
1272 ret = NOTMUCH_STATUS_FILE_ERROR;
1276 if (! keep_backup) {
1277 if (rmtree (backup_path)) {
1278 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1279 backup_path, strerror (errno));
1280 ret = NOTMUCH_STATUS_FILE_ERROR;
1287 notmuch_status_t ret2;
1289 const char *str = notmuch_database_status_string (notmuch);
1290 if (status_cb && str)
1291 status_cb (str, closure);
1293 ret2 = notmuch_database_destroy (notmuch);
1295 /* don't clobber previous error status */
1296 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1300 talloc_free (local);
1306 notmuch_database_destroy (notmuch_database_t *notmuch)
1308 notmuch_status_t status;
1310 status = notmuch_database_close (notmuch);
1311 talloc_free (notmuch);
1317 notmuch_database_get_path (notmuch_database_t *notmuch)
1319 return notmuch->path;
1323 notmuch_database_get_version (notmuch_database_t *notmuch)
1325 unsigned int version;
1326 string version_string;
1330 version_string = notmuch->xapian_db->get_metadata ("version");
1331 if (version_string.empty ())
1334 str = version_string.c_str ();
1335 if (str == NULL || *str == '\0')
1338 version = strtoul (str, &end, 10);
1340 INTERNAL_ERROR ("Malformed database version: %s", str);
1346 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1348 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1349 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1350 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1353 static volatile sig_atomic_t do_progress_notify = 0;
1356 handle_sigalrm (unused (int signal))
1358 do_progress_notify = 1;
1361 /* Upgrade the current database.
1363 * After opening a database in read-write mode, the client should
1364 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1365 * if so, upgrade with this function before making any modifications.
1367 * The optional progress_notify callback can be used by the caller to
1368 * provide progress indication to the user. If non-NULL it will be
1369 * called periodically with 'count' as the number of messages upgraded
1370 * so far and 'total' the overall number of messages that will be
1374 notmuch_database_upgrade (notmuch_database_t *notmuch,
1375 void (*progress_notify) (void *closure,
1379 void *local = talloc_new (NULL);
1380 Xapian::TermIterator t, t_end;
1381 Xapian::WritableDatabase *db;
1382 struct sigaction action;
1383 struct itimerval timerval;
1384 bool timer_is_active = false;
1385 enum _notmuch_features target_features, new_features;
1386 notmuch_status_t status;
1387 notmuch_private_status_t private_status;
1388 notmuch_query_t *query = NULL;
1389 unsigned int count = 0, total = 0;
1391 status = _notmuch_database_ensure_writable (notmuch);
1395 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1397 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1398 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1400 if (! notmuch_database_needs_upgrade (notmuch))
1401 return NOTMUCH_STATUS_SUCCESS;
1403 if (progress_notify) {
1404 /* Set up our handler for SIGALRM */
1405 memset (&action, 0, sizeof (struct sigaction));
1406 action.sa_handler = handle_sigalrm;
1407 sigemptyset (&action.sa_mask);
1408 action.sa_flags = SA_RESTART;
1409 sigaction (SIGALRM, &action, NULL);
1411 /* Then start a timer to send SIGALRM once per second. */
1412 timerval.it_interval.tv_sec = 1;
1413 timerval.it_interval.tv_usec = 0;
1414 timerval.it_value.tv_sec = 1;
1415 timerval.it_value.tv_usec = 0;
1416 setitimer (ITIMER_REAL, &timerval, NULL);
1418 timer_is_active = true;
1421 /* Figure out how much total work we need to do. */
1423 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1424 NOTMUCH_FEATURE_LAST_MOD)) {
1425 query = notmuch_query_create (notmuch, "");
1428 status = notmuch_query_count_messages (query, &msg_count);
1433 notmuch_query_destroy (query);
1436 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1437 t_end = db->allterms_end ("XTIMESTAMP");
1438 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1441 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1442 /* The ghost message upgrade converts all thread_id_*
1443 * metadata values into ghost message documents. */
1444 t_end = db->metadata_keys_end ("thread_id_");
1445 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1449 /* Perform the upgrade in a transaction. */
1450 db->begin_transaction (true);
1452 /* Set the target features so we write out changes in the desired
1454 notmuch->features = target_features;
1456 /* Perform per-message upgrades. */
1458 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1459 NOTMUCH_FEATURE_LAST_MOD)) {
1460 notmuch_messages_t *messages;
1461 notmuch_message_t *message;
1464 query = notmuch_query_create (notmuch, "");
1466 status = notmuch_query_search_messages (query, &messages);
1470 notmuch_messages_valid (messages);
1471 notmuch_messages_move_to_next (messages))
1473 if (do_progress_notify) {
1474 progress_notify (closure, (double) count / total);
1475 do_progress_notify = 0;
1478 message = notmuch_messages_get (messages);
1480 /* Before version 1, each message document had its
1481 * filename in the data field. Copy that into the new
1482 * format by calling notmuch_message_add_filename.
1484 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1485 filename = _notmuch_message_talloc_copy_data (message);
1486 if (filename && *filename != '\0') {
1487 _notmuch_message_add_filename (message, filename);
1488 _notmuch_message_clear_data (message);
1490 talloc_free (filename);
1493 /* Prior to version 2, the "folder:" prefix was
1494 * probabilistic and stemmed. Change it to the current
1495 * boolean prefix. Add "path:" prefixes while at it.
1497 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1498 _notmuch_message_upgrade_folder (message);
1500 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1501 * track modification revisions. Give all messages the
1502 * next available revision; since we just started tracking
1503 * revisions for this database, that will be 1.
1505 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1506 _notmuch_message_upgrade_last_mod (message);
1508 _notmuch_message_sync (message);
1510 notmuch_message_destroy (message);
1515 notmuch_query_destroy (query);
1519 /* Perform per-directory upgrades. */
1521 /* Before version 1 we stored directory timestamps in
1522 * XTIMESTAMP documents instead of the current XDIRECTORY
1523 * documents. So copy those as well. */
1524 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1525 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1527 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1531 Xapian::PostingIterator p, p_end;
1532 std::string term = *t;
1534 p_end = notmuch->xapian_db->postlist_end (term);
1536 for (p = notmuch->xapian_db->postlist_begin (term);
1540 Xapian::Document document;
1542 notmuch_directory_t *directory;
1544 if (do_progress_notify) {
1545 progress_notify (closure, (double) count / total);
1546 do_progress_notify = 0;
1549 document = find_document_for_doc_id (notmuch, *p);
1550 mtime = Xapian::sortable_unserialise (
1551 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1553 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1554 NOTMUCH_FIND_CREATE, &status);
1555 notmuch_directory_set_mtime (directory, mtime);
1556 notmuch_directory_destroy (directory);
1558 db->delete_document (*p);
1565 /* Perform metadata upgrades. */
1567 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1568 * messages were stored as database metadata. Change these to
1571 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1572 notmuch_message_t *message;
1573 std::string message_id, thread_id;
1575 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1576 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1578 if (do_progress_notify) {
1579 progress_notify (closure, (double) count / total);
1580 do_progress_notify = 0;
1583 message_id = (*t).substr (
1584 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1585 thread_id = db->get_metadata (*t);
1587 /* Create ghost message */
1588 message = _notmuch_message_create_for_message_id (
1589 notmuch, message_id.c_str (), &private_status);
1590 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1591 /* Document already exists; ignore the stored thread ID */
1592 } else if (private_status ==
1593 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1594 private_status = _notmuch_message_initialize_ghost (
1595 message, thread_id.c_str ());
1596 if (! private_status)
1597 _notmuch_message_sync (message);
1600 if (private_status) {
1601 _notmuch_database_log (notmuch,
1602 "Upgrade failed while creating ghost messages.\n");
1603 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1607 /* Clear saved metadata thread ID */
1608 db->set_metadata (*t, "");
1614 status = NOTMUCH_STATUS_SUCCESS;
1615 db->set_metadata ("features", _print_features (local, notmuch->features));
1616 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1619 if (status == NOTMUCH_STATUS_SUCCESS)
1620 db->commit_transaction ();
1622 db->cancel_transaction ();
1624 if (timer_is_active) {
1625 /* Now stop the timer. */
1626 timerval.it_interval.tv_sec = 0;
1627 timerval.it_interval.tv_usec = 0;
1628 timerval.it_value.tv_sec = 0;
1629 timerval.it_value.tv_usec = 0;
1630 setitimer (ITIMER_REAL, &timerval, NULL);
1632 /* And disable the signal handler. */
1633 action.sa_handler = SIG_IGN;
1634 sigaction (SIGALRM, &action, NULL);
1638 notmuch_query_destroy (query);
1640 talloc_free (local);
1645 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1647 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1648 notmuch->atomic_nesting > 0)
1651 if (notmuch_database_needs_upgrade (notmuch))
1652 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1655 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1656 } catch (const Xapian::Error &error) {
1657 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1658 error.get_msg().c_str());
1659 notmuch->exception_reported = true;
1660 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1664 notmuch->atomic_nesting++;
1665 return NOTMUCH_STATUS_SUCCESS;
1669 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1671 Xapian::WritableDatabase *db;
1673 if (notmuch->atomic_nesting == 0)
1674 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1676 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1677 notmuch->atomic_nesting > 1)
1680 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1682 db->commit_transaction ();
1684 /* This is a hack for testing. Xapian never flushes on a
1685 * non-flushed commit, even if the flush threshold is 1.
1686 * However, we rely on flushing to test atomicity. */
1687 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1688 if (thresh && atoi (thresh) == 1)
1690 } catch (const Xapian::Error &error) {
1691 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1692 error.get_msg().c_str());
1693 notmuch->exception_reported = true;
1694 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1697 if (notmuch->atomic_dirty) {
1698 ++notmuch->revision;
1699 notmuch->atomic_dirty = false;
1703 notmuch->atomic_nesting--;
1704 return NOTMUCH_STATUS_SUCCESS;
1708 notmuch_database_get_revision (notmuch_database_t *notmuch,
1712 *uuid = notmuch->uuid;
1713 return notmuch->revision;
1716 /* We allow the user to use arbitrarily long paths for directories. But
1717 * we have a term-length limit. So if we exceed that, we'll use the
1718 * SHA-1 of the path for the database term.
1720 * Note: This function may return the original value of 'path'. If it
1721 * does not, then the caller is responsible to free() the returned
1725 _notmuch_database_get_directory_db_path (const char *path)
1727 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1729 if (term_len > NOTMUCH_TERM_MAX)
1730 return _notmuch_sha1_of_string (path);
1735 /* Given a path, split it into two parts: the directory part is all
1736 * components except for the last, and the basename is that last
1737 * component. Getting the return-value for either part is optional
1738 * (the caller can pass NULL).
1740 * The original 'path' can represent either a regular file or a
1741 * directory---the splitting will be carried out in the same way in
1742 * either case. Trailing slashes on 'path' will be ignored, and any
1743 * cases of multiple '/' characters appearing in series will be
1744 * treated as a single '/'.
1746 * Allocation (if any) will have 'ctx' as the talloc owner. But
1747 * pointers will be returned within the original path string whenever
1750 * Note: If 'path' is non-empty and contains no non-trailing slash,
1751 * (that is, consists of a filename with no parent directory), then
1752 * the directory returned will be an empty string. However, if 'path'
1753 * is an empty string, then both directory and basename will be
1757 _notmuch_database_split_path (void *ctx,
1759 const char **directory,
1760 const char **basename)
1764 if (path == NULL || *path == '\0') {
1769 return NOTMUCH_STATUS_SUCCESS;
1772 /* Find the last slash (not counting a trailing slash), if any. */
1774 slash = path + strlen (path) - 1;
1776 /* First, skip trailing slashes. */
1777 while (slash != path && *slash == '/')
1780 /* Then, find a slash. */
1781 while (slash != path && *slash != '/') {
1788 /* Finally, skip multiple slashes. */
1789 while (slash != path && *(slash - 1) == '/')
1792 if (slash == path) {
1794 *directory = talloc_strdup (ctx, "");
1799 *directory = talloc_strndup (ctx, path, slash - path);
1802 return NOTMUCH_STATUS_SUCCESS;
1805 /* Find the document ID of the specified directory.
1807 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1808 * created if one does not exist for 'path'. Otherwise, if the
1809 * directory document does not exist, this sets *directory_id to
1810 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1813 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1815 notmuch_find_flags_t flags,
1816 unsigned int *directory_id)
1818 notmuch_directory_t *directory;
1819 notmuch_status_t status;
1823 return NOTMUCH_STATUS_SUCCESS;
1826 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1827 if (status || !directory) {
1832 *directory_id = _notmuch_directory_get_document_id (directory);
1834 notmuch_directory_destroy (directory);
1836 return NOTMUCH_STATUS_SUCCESS;
1840 _notmuch_database_get_directory_path (void *ctx,
1841 notmuch_database_t *notmuch,
1842 unsigned int doc_id)
1844 Xapian::Document document;
1846 document = find_document_for_doc_id (notmuch, doc_id);
1848 return talloc_strdup (ctx, document.get_data ().c_str ());
1851 /* Given a legal 'filename' for the database, (either relative to
1852 * database path or absolute with initial components identical to
1853 * database path), return a new string (with 'ctx' as the talloc
1854 * owner) suitable for use as a direntry term value.
1856 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1857 * will be created in the database as needed. Otherwise, if the
1858 * necessary directory documents do not exist, this sets
1859 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1862 _notmuch_database_filename_to_direntry (void *ctx,
1863 notmuch_database_t *notmuch,
1864 const char *filename,
1865 notmuch_find_flags_t flags,
1868 const char *relative, *directory, *basename;
1869 Xapian::docid directory_id;
1870 notmuch_status_t status;
1872 relative = _notmuch_database_relative_path (notmuch, filename);
1874 status = _notmuch_database_split_path (ctx, relative,
1875 &directory, &basename);
1879 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1881 if (status || directory_id == (unsigned int)-1) {
1886 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1888 return NOTMUCH_STATUS_SUCCESS;
1891 /* Given a legal 'path' for the database, return the relative path.
1893 * The return value will be a pointer to the original path contents,
1894 * and will be either the original string (if 'path' was relative) or
1895 * a portion of the string (if path was absolute and begins with the
1899 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1902 const char *db_path, *relative;
1903 unsigned int db_path_len;
1905 db_path = notmuch_database_get_path (notmuch);
1906 db_path_len = strlen (db_path);
1910 if (*relative == '/') {
1911 while (*relative == '/' && *(relative+1) == '/')
1914 if (strncmp (relative, db_path, db_path_len) == 0)
1916 relative += db_path_len;
1917 while (*relative == '/')
1926 notmuch_database_get_directory (notmuch_database_t *notmuch,
1928 notmuch_directory_t **directory)
1930 notmuch_status_t status;
1932 if (directory == NULL)
1933 return NOTMUCH_STATUS_NULL_POINTER;
1937 *directory = _notmuch_directory_create (notmuch, path,
1938 NOTMUCH_FIND_LOOKUP, &status);
1939 } catch (const Xapian::Error &error) {
1940 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1941 error.get_msg().c_str());
1942 notmuch->exception_reported = true;
1943 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1948 /* Allocate a document ID that satisfies the following criteria:
1950 * 1. The ID does not exist for any document in the Xapian database
1952 * 2. The ID was not previously returned from this function
1954 * 3. The ID is the smallest integer satisfying (1) and (2)
1956 * This function will trigger an internal error if these constraints
1957 * cannot all be satisfied, (that is, the pool of available document
1958 * IDs has been exhausted).
1961 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1963 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1965 notmuch->last_doc_id++;
1967 if (notmuch->last_doc_id == 0)
1968 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1970 return notmuch->last_doc_id;
1974 notmuch_database_remove_message (notmuch_database_t *notmuch,
1975 const char *filename)
1977 notmuch_status_t status;
1978 notmuch_message_t *message;
1980 status = notmuch_database_find_message_by_filename (notmuch, filename,
1983 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1984 status = _notmuch_message_remove_filename (message, filename);
1985 if (status == NOTMUCH_STATUS_SUCCESS)
1986 _notmuch_message_delete (message);
1987 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1988 _notmuch_message_sync (message);
1990 notmuch_message_destroy (message);
1997 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1998 const char *filename,
1999 notmuch_message_t **message_ret)
2002 const char *prefix = _find_prefix ("file-direntry");
2003 char *direntry, *term;
2004 Xapian::PostingIterator i, end;
2005 notmuch_status_t status;
2007 if (message_ret == NULL)
2008 return NOTMUCH_STATUS_NULL_POINTER;
2010 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2011 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2013 /* return NULL on any failure */
2014 *message_ret = NULL;
2016 local = talloc_new (notmuch);
2019 status = _notmuch_database_filename_to_direntry (
2020 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2021 if (status || !direntry)
2024 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2026 find_doc_ids_for_term (notmuch, term, &i, &end);
2029 notmuch_private_status_t private_status;
2031 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2033 if (*message_ret == NULL)
2034 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2036 } catch (const Xapian::Error &error) {
2037 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2038 error.get_msg().c_str());
2039 notmuch->exception_reported = true;
2040 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2044 talloc_free (local);
2046 if (status && *message_ret) {
2047 notmuch_message_destroy (*message_ret);
2048 *message_ret = NULL;
2053 notmuch_string_list_t *
2054 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2055 Xapian::TermIterator &end,
2058 int prefix_len = strlen (prefix);
2059 notmuch_string_list_t *list;
2061 list = _notmuch_string_list_create (ctx);
2062 if (unlikely (list == NULL))
2065 for (i.skip_to (prefix); i != end; i++) {
2066 /* Terminate loop at first term without desired prefix. */
2067 if (strncmp ((*i).c_str (), prefix, prefix_len))
2070 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2077 notmuch_database_get_all_tags (notmuch_database_t *db)
2079 Xapian::TermIterator i, end;
2080 notmuch_string_list_t *tags;
2083 i = db->xapian_db->allterms_begin();
2084 end = db->xapian_db->allterms_end();
2085 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2086 _find_prefix ("tag"));
2087 _notmuch_string_list_sort (tags);
2088 return _notmuch_tags_create (db, tags);
2089 } catch (const Xapian::Error &error) {
2090 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2091 error.get_msg().c_str());
2092 db->exception_reported = true;
2098 notmuch_database_status_string (const notmuch_database_t *notmuch)
2100 return notmuch->status_string;