1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "thread-fp.h"
25 #include "regexp-fields.h"
26 #include "string-util.h"
35 #include <glib.h> /* g_free, GPtrArray, GHashTable */
36 #include <glib-object.h> /* g_type_init */
38 #include <gmime/gmime.h> /* g_mime_init */
42 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
47 notmuch_field_flag_t flags;
50 #define NOTMUCH_DATABASE_VERSION 3
52 #define STRINGIFY(s) _SUB_STRINGIFY (s)
53 #define _SUB_STRINGIFY(s) #s
55 #if HAVE_XAPIAN_DB_RETRY_LOCK
56 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
58 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
61 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
64 _log_xapian_exception (const char *where, notmuch_database_t *notmuch, const Xapian::Error error) {
65 _notmuch_database_log (notmuch,
66 "A Xapian exception occurred at %s: %s\n",
68 error.get_msg ().c_str ());
69 notmuch->exception_reported = true;
72 notmuch_database_mode_t
73 _notmuch_database_mode (notmuch_database_t *notmuch)
78 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
80 * We currently have three different types of documents (mail, ghost,
81 * and directory) and also some metadata.
83 * There are two kinds of prefixes used in notmuch. There are the
84 * human friendly 'prefix names' like "thread:", which are also used
85 * in the query parser, and the actual prefix terms in the database
86 * (e.g. "G"). The correspondence is maintained in the file scope data
87 * structure 'prefix_table'.
91 * A mail document is associated with a particular email message. It
92 * is stored in one or more files on disk and is uniquely identified
93 * by its "id" field (which is generally the message ID). It is
94 * indexed with the following prefixed terms which the database uses
95 * to construct threads, etc.:
97 * Single terms of given prefix:
101 * id: Unique ID of mail. This is from the Message-ID header
102 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
103 * If it's present and too long, then we use
104 * "notmuch-sha1-<sha1_sum_of_message_id>".
105 * If this header is not present, we use
106 * "notmuch-sha1-<sha1_sum_of_entire_file>".
108 * thread: The ID of the thread to which the mail belongs
110 * replyto: The ID from the In-Reply-To header of the mail (if any).
112 * Multiple terms of given prefix:
114 * reference: All message IDs from In-Reply-To and References
115 * headers in the message.
117 * tag: Any tags associated with this message by the user.
119 * file-direntry: A colon-separated pair of values
120 * (INTEGER:STRING), where INTEGER is the
121 * document ID of a directory document, and
122 * STRING is the name of a file within that
123 * directory for this mail message.
125 * property: Has a property with key=value
126 * FIXME: if no = is present, should match on any value
128 * A mail document also has four values:
130 * TIMESTAMP: The time_t value corresponding to the message's
133 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
135 * FROM: The value of the "From" header
137 * SUBJECT: The value of the "Subject" header
139 * LAST_MOD: The revision number as of the last tag or
142 * The prefixed terms described above are also searchable without an
143 * explicit field name, but as of notmuch 0.29 this is due to
144 * query-parser setup, not extra terms in the database. In addition,
145 * terms from the content of the message are added without a prefix
146 * for use by the user in searching. Note that the prefix name "body"
147 * is used to refer to the empty prefix string in the database.
149 * The path of the containing folder is added with the "folder" prefix
150 * (see _notmuch_message_add_folder_terms). Sub-paths of the the path
151 * of the mail message are added with the "path" prefix.
153 * The data portion of a mail document is empty.
155 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
156 * -----------------------------------------------
157 * A ghost mail document is like a mail document, but where we don't
158 * have the message content. These are used to track thread reference
159 * information for messages we haven't received.
161 * A ghost mail document has type: ghost; id and thread fields that
162 * are identical to the mail document fields; and a MESSAGE_ID value.
166 * A directory document is used by a client of the notmuch library to
167 * maintain data necessary to allow for efficient polling of mail
170 * All directory documents contain one term:
172 * directory: The directory path (relative to the database path)
173 * Or the SHA1 sum of the directory path (if the
174 * path itself is too long to fit in a Xapian
177 * And all directory documents for directories other than top-level
178 * directories also contain the following term:
180 * directory-direntry: A colon-separated pair of values
181 * (INTEGER:STRING), where INTEGER is the
182 * document ID of the parent directory
183 * document, and STRING is the name of this
184 * directory within that parent.
186 * All directory documents have a single value:
188 * TIMESTAMP: The mtime of the directory (at last scan)
190 * The data portion of a directory document contains the path of the
191 * directory (relative to the database path).
195 * Xapian allows us to store arbitrary name-value pairs as
196 * "metadata". We currently use the following metadata names with the
199 * version The database schema version, (which is distinct
200 * from both the notmuch package version (see
201 * notmuch --version) and the libnotmuch library
202 * version. The version is stored as an base-10
203 * ASCII integer. The initial database version
204 * was 1, (though a schema existed before that
205 * were no "version" database value existed at
206 * all). Successive versions are allocated as
207 * changes are made to the database (such as by
208 * indexing new fields).
210 * features The set of features supported by this
211 * database. This consists of a set of
212 * '\n'-separated lines, where each is a feature
213 * name, a '\t', and compatibility flags. If the
214 * compatibility flags contain 'w', then the
215 * opener must support this feature to safely
216 * write this database. If the compatibility
217 * flags contain 'r', then the opener must
218 * support this feature to read this database.
219 * Introduced in database version 3.
221 * last_thread_id The last thread ID generated. This is stored
222 * as a 16-byte hexadecimal ASCII representation
223 * of a 64-bit unsigned integer. The first ID
224 * generated is 1 and the value will be
225 * incremented for each thread ID.
227 * C* metadata keys starting with C indicate
228 * configuration data. It can be managed with the
229 * n_database_*config* API. There is a convention
230 * of hierarchical keys separated by '.' (e.g.
231 * query.notmuch stores the value for the named
232 * query 'notmuch'), but it is not enforced by the
238 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
239 * Instead, the database has the following additional database
242 * thread_id_* A pre-allocated thread ID for a particular
243 * message. This is actually an arbitrarily large
244 * family of metadata name. Any particular name is
245 * formed by concatenating "thread_id_" with a message
246 * ID (or the SHA1 sum of a message ID if it is very
247 * long---see description of 'id' in the mail
248 * document). The value stored is a thread ID.
250 * These thread ID metadata values are stored
251 * whenever a message references a parent message
252 * that does not yet exist in the database. A
253 * thread ID will be allocated and stored, and if
254 * the message is later added, the stored thread
255 * ID will be used (and the metadata value will
258 * Even before a message is added, it's
259 * pre-allocated thread ID is useful so that all
260 * descendant messages that reference this common
261 * parent can be recognized as belonging to the
265 /* With these prefix values we follow the conventions published here:
267 * https://xapian.org/docs/omega/termprefixes.html
269 * as much as makes sense. Note that I took some liberty in matching
270 * the reserved prefix values to notmuch concepts, (for example, 'G'
271 * is documented as "newsGroup (or similar entity - e.g. a web forum
272 * name)", for which I think the thread is the closest analogue in
273 * notmuch. This in spite of the fact that we will eventually be
274 * storing mailing-list messages where 'G' for "mailing list name"
275 * might be even a closer analogue. I'm treating the single-character
276 * prefixes preferentially for core notmuch concepts (which will be
277 * nearly universal to all mail messages).
281 prefix_t prefix_table[] = {
282 /* name term prefix flags */
283 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
284 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
285 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
286 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
287 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
288 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
289 { "body", "", NOTMUCH_FIELD_EXTERNAL |
290 NOTMUCH_FIELD_PROBABILISTIC },
291 { "thread", "G", NOTMUCH_FIELD_EXTERNAL |
292 NOTMUCH_FIELD_PROCESSOR },
293 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
294 NOTMUCH_FIELD_PROCESSOR },
295 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
296 NOTMUCH_FIELD_PROCESSOR },
297 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
298 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
299 NOTMUCH_FIELD_PROCESSOR },
300 { "path", "P", NOTMUCH_FIELD_EXTERNAL |
301 NOTMUCH_FIELD_PROCESSOR },
302 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
304 * Unconditionally add ':' to reduce potential ambiguity with
305 * overlapping prefixes and/or terms that start with capital
306 * letters. See Xapian document termprefixes.html for related
309 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
310 NOTMUCH_FIELD_PROCESSOR },
311 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
312 NOTMUCH_FIELD_PROCESSOR },
313 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
314 NOTMUCH_FIELD_PROCESSOR },
315 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
316 NOTMUCH_FIELD_PROBABILISTIC |
317 NOTMUCH_FIELD_PROCESSOR },
318 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
319 NOTMUCH_FIELD_PROBABILISTIC },
320 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
321 NOTMUCH_FIELD_PROBABILISTIC },
322 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
323 NOTMUCH_FIELD_PROBABILISTIC },
324 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
325 NOTMUCH_FIELD_PROBABILISTIC |
326 NOTMUCH_FIELD_PROCESSOR },
330 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
333 notmuch->query_parser->add_prefix ("", prefix->prefix);
334 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
335 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
337 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
340 notmuch_string_map_iterator_t *
341 _notmuch_database_user_headers (notmuch_database_t *notmuch)
343 return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
347 _user_prefix (void *ctx, const char *name)
349 return talloc_asprintf (ctx, "XU%s:", name);
352 static notmuch_status_t
353 _setup_user_query_fields (notmuch_database_t *notmuch)
355 notmuch_config_list_t *list;
356 notmuch_status_t status;
358 notmuch->user_prefix = _notmuch_string_map_create (notmuch);
359 if (notmuch->user_prefix == NULL)
360 return NOTMUCH_STATUS_OUT_OF_MEMORY;
362 notmuch->user_header = _notmuch_string_map_create (notmuch);
363 if (notmuch->user_header == NULL)
364 return NOTMUCH_STATUS_OUT_OF_MEMORY;
366 status = notmuch_database_get_config_list (notmuch, CONFIG_HEADER_PREFIX, &list);
370 for (; notmuch_config_list_valid (list); notmuch_config_list_move_to_next (list)) {
372 prefix_t query_field;
374 const char *key = notmuch_config_list_key (list)
375 + sizeof (CONFIG_HEADER_PREFIX) - 1;
377 _notmuch_string_map_append (notmuch->user_prefix,
379 _user_prefix (notmuch, key));
381 _notmuch_string_map_append (notmuch->user_header,
383 notmuch_config_list_value (list));
385 query_field.name = talloc_strdup (notmuch, key);
386 query_field.prefix = _user_prefix (notmuch, key);
387 query_field.flags = NOTMUCH_FIELD_PROBABILISTIC
388 | NOTMUCH_FIELD_EXTERNAL;
390 _setup_query_field_default (&query_field, notmuch);
393 notmuch_config_list_destroy (list);
395 return NOTMUCH_STATUS_SUCCESS;
399 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
401 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
402 Xapian::FieldProcessor *fp;
404 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
405 fp = (new DateFieldProcessor(NOTMUCH_VALUE_TIMESTAMP))->release ();
406 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
407 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
408 else if (STRNCMP_LITERAL (prefix->name, "thread") == 0)
409 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
411 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
412 *notmuch->query_parser, notmuch))->release ();
414 /* we treat all field-processor fields as boolean in order to get the raw input */
416 notmuch->query_parser->add_prefix ("", prefix->prefix);
417 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
419 _setup_query_field_default (prefix, notmuch);
424 _find_prefix (const char *name)
428 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
429 if (strcmp (name, prefix_table[i].name) == 0)
430 return prefix_table[i].prefix;
433 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
438 /* Like find prefix, but include the possibility of user defined
439 * prefixes specific to this database */
442 _notmuch_database_prefix (notmuch_database_t *notmuch, const char *name)
446 /*XXX TODO: reduce code duplication */
447 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
448 if (strcmp (name, prefix_table[i].name) == 0)
449 return prefix_table[i].prefix;
452 if (notmuch->user_prefix)
453 return _notmuch_string_map_get (notmuch->user_prefix, name);
458 static const struct {
459 /* NOTMUCH_FEATURE_* value. */
460 _notmuch_features value;
461 /* Feature name as it appears in the database. This name should
462 * be appropriate for displaying to the user if an older version
463 * of notmuch doesn't support this feature. */
465 /* Compatibility flags when this feature is declared. */
467 } feature_names[] = {
468 { NOTMUCH_FEATURE_FILE_TERMS,
469 "multiple paths per message", "rw" },
470 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
471 "relative directory paths", "rw" },
472 /* Header values are not required for reading a database because a
473 * reader can just refer to the message file. */
474 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
475 "from/subject/message-ID in database", "w" },
476 { NOTMUCH_FEATURE_BOOL_FOLDER,
477 "exact folder:/path: search", "rw" },
478 { NOTMUCH_FEATURE_GHOSTS,
479 "mail documents for missing messages", "w" },
480 /* Knowledge of the index mime-types are not required for reading
481 * a database because a reader will just be unable to query
483 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
484 "indexed MIME types", "w" },
485 { NOTMUCH_FEATURE_LAST_MOD,
486 "modification tracking", "w" },
487 /* Existing databases will work fine for all queries not involving
489 { NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY,
490 "index body and headers separately", "w" },
494 notmuch_status_to_string (notmuch_status_t status)
497 case NOTMUCH_STATUS_SUCCESS:
498 return "No error occurred";
499 case NOTMUCH_STATUS_OUT_OF_MEMORY:
500 return "Out of memory";
501 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
502 return "Attempt to write to a read-only database";
503 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
504 return "A Xapian exception occurred";
505 case NOTMUCH_STATUS_FILE_ERROR:
506 return "Something went wrong trying to read or write a file";
507 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
508 return "File is not an email";
509 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
510 return "Message ID is identical to a message in database";
511 case NOTMUCH_STATUS_NULL_POINTER:
512 return "Erroneous NULL pointer";
513 case NOTMUCH_STATUS_TAG_TOO_LONG:
514 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
515 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
516 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
517 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
518 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
519 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
520 return "Unsupported operation";
521 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
522 return "Operation requires a database upgrade";
523 case NOTMUCH_STATUS_PATH_ERROR:
524 return "Path supplied is illegal for this function";
525 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
526 return "Crypto protocol missing, malformed, or unintelligible";
527 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
528 return "Crypto engine initialization failure";
529 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
530 return "Unknown crypto protocol";
532 case NOTMUCH_STATUS_LAST_STATUS:
533 return "Unknown error status value";
538 _notmuch_database_log (notmuch_database_t *notmuch,
544 va_start (va_args, format);
546 if (notmuch->status_string)
547 talloc_free (notmuch->status_string);
549 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
554 _notmuch_database_log_append (notmuch_database_t *notmuch,
560 va_start (va_args, format);
562 if (notmuch->status_string)
563 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
565 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
571 find_doc_ids_for_term (notmuch_database_t *notmuch,
573 Xapian::PostingIterator *begin,
574 Xapian::PostingIterator *end)
576 *begin = notmuch->xapian_db->postlist_begin (term);
578 *end = notmuch->xapian_db->postlist_end (term);
582 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
583 const char *prefix_name,
585 Xapian::PostingIterator *begin,
586 Xapian::PostingIterator *end)
590 term = talloc_asprintf (notmuch, "%s%s",
591 _find_prefix (prefix_name), value);
593 find_doc_ids_for_term (notmuch, term, begin, end);
598 notmuch_private_status_t
599 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
600 const char *prefix_name,
602 unsigned int *doc_id)
604 Xapian::PostingIterator i, end;
606 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
610 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
615 #if DEBUG_DATABASE_SANITY
619 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
623 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
626 static Xapian::Document
627 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
629 return notmuch->xapian_db->get_document (doc_id);
632 /* Generate a compressed version of 'message_id' of the form:
634 * notmuch-sha1-<sha1_sum_of_message_id>
637 _notmuch_message_id_compressed (void *ctx, const char *message_id)
639 char *sha1, *compressed;
641 sha1 = _notmuch_sha1_of_string (message_id);
643 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
650 notmuch_database_find_message (notmuch_database_t *notmuch,
651 const char *message_id,
652 notmuch_message_t **message_ret)
654 notmuch_private_status_t status;
657 if (message_ret == NULL)
658 return NOTMUCH_STATUS_NULL_POINTER;
660 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
661 message_id = _notmuch_message_id_compressed (notmuch, message_id);
664 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
665 message_id, &doc_id);
667 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
670 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
672 if (*message_ret == NULL)
673 return NOTMUCH_STATUS_OUT_OF_MEMORY;
676 return NOTMUCH_STATUS_SUCCESS;
677 } catch (const Xapian::Error &error) {
678 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
679 error.get_msg ().c_str ());
680 notmuch->exception_reported = true;
682 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
687 notmuch_database_create (const char *path, notmuch_database_t **database)
689 char *status_string = NULL;
690 notmuch_status_t status;
692 status = notmuch_database_create_verbose (path, database,
696 fputs (status_string, stderr);
697 free (status_string);
704 notmuch_database_create_verbose (const char *path,
705 notmuch_database_t **database,
706 char **status_string)
708 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
709 notmuch_database_t *notmuch = NULL;
710 char *notmuch_path = NULL;
711 char *message = NULL;
716 message = strdup ("Error: Cannot create a database for a NULL path.\n");
717 status = NOTMUCH_STATUS_NULL_POINTER;
721 if (path[0] != '/') {
722 message = strdup ("Error: Database path must be absolute.\n");
723 status = NOTMUCH_STATUS_PATH_ERROR;
727 err = stat (path, &st);
729 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
730 path, strerror (errno)));
731 status = NOTMUCH_STATUS_FILE_ERROR;
735 if (! S_ISDIR (st.st_mode)) {
736 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
737 "Not a directory.\n",
739 status = NOTMUCH_STATUS_FILE_ERROR;
743 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
745 err = mkdir (notmuch_path, 0755);
748 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
749 notmuch_path, strerror (errno)));
750 status = NOTMUCH_STATUS_FILE_ERROR;
754 status = notmuch_database_open_verbose (path,
755 NOTMUCH_DATABASE_MODE_READ_WRITE,
760 /* Upgrade doesn't add these feature to existing databases, but
761 * new databases have them. */
762 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
763 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
764 notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
766 status = notmuch_database_upgrade (notmuch, NULL, NULL);
768 notmuch_database_close (notmuch);
774 talloc_free (notmuch_path);
778 *status_string = message;
785 talloc_free (notmuch);
790 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
792 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY) {
793 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
794 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
797 return NOTMUCH_STATUS_SUCCESS;
800 /* Allocate a revision number for the next change. */
802 _notmuch_database_new_revision (notmuch_database_t *notmuch)
804 unsigned long new_revision = notmuch->revision + 1;
806 /* If we're in an atomic section, hold off on updating the
807 * committed revision number until we commit the atomic section.
809 if (notmuch->atomic_nesting)
810 notmuch->atomic_dirty = true;
812 notmuch->revision = new_revision;
817 /* Parse a database features string from the given database version.
818 * Returns the feature bit set.
820 * For version < 3, this ignores the features string and returns a
821 * hard-coded set of features.
823 * If there are unrecognized features that are required to open the
824 * database in mode (which should be 'r' or 'w'), return a
825 * comma-separated list of unrecognized but required features in
826 * *incompat_out suitable for presenting to the user. *incompat_out
827 * will be allocated from ctx.
829 static _notmuch_features
830 _parse_features (const void *ctx, const char *features, unsigned int version,
831 char mode, char **incompat_out)
833 _notmuch_features res = static_cast<_notmuch_features>(0);
834 unsigned int namelen, i;
838 /* Prior to database version 3, features were implied by the
841 return NOTMUCH_FEATURES_V0;
842 else if (version == 1)
843 return NOTMUCH_FEATURES_V1;
844 else if (version == 2)
845 return NOTMUCH_FEATURES_V2;
847 /* Parse the features string */
848 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
849 flags = strchr (features, '\t');
850 if (! flags || flags > features + llen)
852 namelen = flags - features;
854 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
855 if (strlen (feature_names[i].name) == namelen &&
856 strncmp (feature_names[i].name, features, namelen) == 0) {
857 res |= feature_names[i].value;
862 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
863 /* Unrecognized feature */
864 const char *have = strchr (flags, mode);
865 if (have && have < features + llen) {
866 /* This feature is required to access this database in
867 * 'mode', but we don't understand it. */
869 *incompat_out = talloc_strdup (ctx, "");
870 *incompat_out = talloc_asprintf_append_buffer (
871 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
881 _print_features (const void *ctx, unsigned int features)
884 char *res = talloc_strdup (ctx, "");
886 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
887 if (features & feature_names[i].value)
888 res = talloc_asprintf_append_buffer (
889 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
895 notmuch_database_open (const char *path,
896 notmuch_database_mode_t mode,
897 notmuch_database_t **database)
899 char *status_string = NULL;
900 notmuch_status_t status;
902 status = notmuch_database_open_verbose (path, mode, database,
906 fputs (status_string, stderr);
907 free (status_string);
914 notmuch_database_open_verbose (const char *path,
915 notmuch_database_mode_t mode,
916 notmuch_database_t **database,
917 char **status_string)
919 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
920 void *local = talloc_new (NULL);
921 notmuch_database_t *notmuch = NULL;
922 char *notmuch_path, *xapian_path, *incompat_features;
923 char *message = NULL;
926 unsigned int i, version;
927 static int initialized = 0;
930 message = strdup ("Error: Cannot open a database for a NULL path.\n");
931 status = NOTMUCH_STATUS_NULL_POINTER;
935 if (path[0] != '/') {
936 message = strdup ("Error: Database path must be absolute.\n");
937 status = NOTMUCH_STATUS_PATH_ERROR;
941 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
942 message = strdup ("Out of memory\n");
943 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
947 err = stat (notmuch_path, &st);
949 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
950 notmuch_path, strerror (errno)));
951 status = NOTMUCH_STATUS_FILE_ERROR;
955 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
956 message = strdup ("Out of memory\n");
957 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
961 /* Initialize the GLib type system and threads */
962 #if ! GLIB_CHECK_VERSION (2, 35, 1)
966 /* Initialize gmime */
972 notmuch = talloc_zero (NULL, notmuch_database_t);
973 notmuch->exception_reported = false;
974 notmuch->status_string = NULL;
975 notmuch->path = talloc_strdup (notmuch, path);
977 strip_trailing (notmuch->path, '/');
979 notmuch->mode = mode;
980 notmuch->atomic_nesting = 0;
983 string last_thread_id;
986 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
987 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
990 notmuch->xapian_db = new Xapian::Database (xapian_path);
993 /* Check version. As of database version 3, we represent
994 * changes in terms of features, so assume a version bump
995 * means a dramatically incompatible change. */
996 version = notmuch_database_get_version (notmuch);
997 if (version > NOTMUCH_DATABASE_VERSION) {
998 IGNORE_RESULT (asprintf (&message,
999 "Error: Notmuch database at %s\n"
1000 " has a newer database format version (%u) than supported by this\n"
1001 " version of notmuch (%u).\n",
1002 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
1003 notmuch_database_destroy (notmuch);
1005 status = NOTMUCH_STATUS_FILE_ERROR;
1009 /* Check features. */
1010 incompat_features = NULL;
1011 notmuch->features = _parse_features (
1012 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1013 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1014 &incompat_features);
1015 if (incompat_features) {
1016 IGNORE_RESULT (asprintf (&message,
1017 "Error: Notmuch database at %s\n"
1018 " requires features (%s)\n"
1019 " not supported by this version of notmuch.\n",
1020 notmuch_path, incompat_features));
1021 notmuch_database_destroy (notmuch);
1023 status = NOTMUCH_STATUS_FILE_ERROR;
1027 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1028 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1029 if (last_thread_id.empty ()) {
1030 notmuch->last_thread_id = 0;
1035 str = last_thread_id.c_str ();
1036 notmuch->last_thread_id = strtoull (str, &end, 16);
1038 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1041 /* Get current highest revision number. */
1042 last_mod = notmuch->xapian_db->get_value_upper_bound (
1043 NOTMUCH_VALUE_LAST_MOD);
1044 if (last_mod.empty ())
1045 notmuch->revision = 0;
1047 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1048 notmuch->uuid = talloc_strdup (
1049 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1051 notmuch->query_parser = new Xapian::QueryParser;
1052 notmuch->term_gen = new Xapian::TermGenerator;
1053 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1054 notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1055 notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP, "date:");
1056 notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1057 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1058 notmuch->query_parser->set_database (*notmuch->xapian_db);
1059 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1060 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1061 notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
1062 notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
1063 notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
1065 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1066 const prefix_t *prefix = &prefix_table[i];
1067 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1068 _setup_query_field (prefix, notmuch);
1071 status = _setup_user_query_fields (notmuch);
1072 } catch (const Xapian::Error &error) {
1073 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1074 error.get_msg ().c_str ()));
1075 notmuch_database_destroy (notmuch);
1077 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1081 talloc_free (local);
1085 *status_string = message;
1091 *database = notmuch;
1093 talloc_free (notmuch);
1096 notmuch->open = true;
1102 notmuch_database_close (notmuch_database_t *notmuch)
1104 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1106 /* Many Xapian objects (and thus notmuch objects) hold references to
1107 * the database, so merely deleting the database may not suffice to
1108 * close it. Thus, we explicitly close it here. */
1109 if (notmuch->open) {
1111 /* If there's an outstanding transaction, it's unclear if
1112 * closing the Xapian database commits everything up to
1113 * that transaction, or may discard committed (but
1114 * unflushed) transactions. To be certain, explicitly
1115 * cancel any outstanding transaction before closing. */
1116 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1117 notmuch->atomic_nesting)
1118 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1119 ->cancel_transaction ();
1121 /* Close the database. This implicitly flushes
1122 * outstanding changes. */
1123 notmuch->xapian_db->close ();
1124 } catch (const Xapian::Error &error) {
1125 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1126 if (! notmuch->exception_reported) {
1127 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1128 error.get_msg ().c_str ());
1132 notmuch->open = false;
1137 _notmuch_database_reopen (notmuch_database_t *notmuch)
1139 if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_ONLY)
1140 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1143 notmuch->xapian_db->reopen ();
1144 } catch (const Xapian::Error &error) {
1145 if (! notmuch->exception_reported) {
1146 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1147 error.get_msg ().c_str ());
1148 notmuch->exception_reported = true;
1150 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1155 return NOTMUCH_STATUS_SUCCESS;
1159 unlink_cb (const char *path,
1160 unused (const struct stat *sb),
1162 unused (struct FTW *ftw))
1164 return remove (path);
1168 rmtree (const char *path)
1170 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1173 class NotmuchCompactor : public Xapian::Compactor
1175 notmuch_compact_status_cb_t status_cb;
1176 void *status_closure;
1179 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1180 status_cb (cb), status_closure (closure)
1185 set_status (const std::string &table, const std::string &status)
1189 if (status_cb == NULL)
1192 if (status.length () == 0)
1193 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
1195 msg = talloc_asprintf (NULL, " %s", status.c_str ());
1201 status_cb (msg, status_closure);
1206 /* Compacts the given database, optionally saving the original database
1207 * in backup_path. Additionally, a callback function can be provided to
1208 * give the user feedback on the progress of the (likely long-lived)
1209 * compaction process.
1211 * The backup path must point to a directory on the same volume as the
1212 * original database. Passing a NULL backup_path will result in the
1213 * uncompacted database being deleted after compaction has finished.
1214 * Note that the database write lock will be held during the
1215 * compaction process to protect data integrity.
1218 notmuch_database_compact (const char *path,
1219 const char *backup_path,
1220 notmuch_compact_status_cb_t status_cb,
1224 char *notmuch_path, *xapian_path, *compact_xapian_path;
1225 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1226 notmuch_database_t *notmuch = NULL;
1227 struct stat statbuf;
1229 char *message = NULL;
1231 local = talloc_new (NULL);
1233 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1235 ret = notmuch_database_open_verbose (path,
1236 NOTMUCH_DATABASE_MODE_READ_WRITE,
1240 if (status_cb) status_cb (message, closure);
1244 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1245 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1249 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1250 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1254 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1255 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1259 if (backup_path == NULL) {
1260 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1261 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1264 keep_backup = false;
1269 if (stat (backup_path, &statbuf) != -1) {
1270 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1271 ret = NOTMUCH_STATUS_FILE_ERROR;
1274 if (errno != ENOENT) {
1275 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1277 ret = NOTMUCH_STATUS_FILE_ERROR;
1281 /* Unconditionally attempt to remove old work-in-progress database (if
1282 * any). This is "protected" by database lock. If this fails due to write
1283 * errors (etc), the following code will fail and provide error message.
1285 (void) rmtree (compact_xapian_path);
1288 NotmuchCompactor compactor (status_cb, closure);
1289 notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0, compactor);
1290 } catch (const Xapian::Error &error) {
1291 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
1292 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1296 if (rename (xapian_path, backup_path)) {
1297 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1298 xapian_path, backup_path, strerror (errno));
1299 ret = NOTMUCH_STATUS_FILE_ERROR;
1303 if (rename (compact_xapian_path, xapian_path)) {
1304 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1305 compact_xapian_path, xapian_path, strerror (errno));
1306 ret = NOTMUCH_STATUS_FILE_ERROR;
1310 if (! keep_backup) {
1311 if (rmtree (backup_path)) {
1312 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1313 backup_path, strerror (errno));
1314 ret = NOTMUCH_STATUS_FILE_ERROR;
1321 notmuch_status_t ret2;
1323 const char *str = notmuch_database_status_string (notmuch);
1324 if (status_cb && str)
1325 status_cb (str, closure);
1327 ret2 = notmuch_database_destroy (notmuch);
1329 /* don't clobber previous error status */
1330 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1334 talloc_free (local);
1340 notmuch_database_destroy (notmuch_database_t *notmuch)
1342 notmuch_status_t status;
1344 status = notmuch_database_close (notmuch);
1346 delete notmuch->term_gen;
1347 notmuch->term_gen = NULL;
1348 delete notmuch->query_parser;
1349 notmuch->query_parser = NULL;
1350 delete notmuch->xapian_db;
1351 notmuch->xapian_db = NULL;
1352 delete notmuch->value_range_processor;
1353 notmuch->value_range_processor = NULL;
1354 delete notmuch->date_range_processor;
1355 notmuch->date_range_processor = NULL;
1356 delete notmuch->last_mod_range_processor;
1357 notmuch->last_mod_range_processor = NULL;
1359 talloc_free (notmuch);
1365 notmuch_database_get_path (notmuch_database_t *notmuch)
1367 return notmuch->path;
1371 notmuch_database_get_version (notmuch_database_t *notmuch)
1373 unsigned int version;
1374 string version_string;
1379 version_string = notmuch->xapian_db->get_metadata ("version");
1380 } catch (const Xapian::Error &error) {
1381 LOG_XAPIAN_EXCEPTION (notmuch, error);
1385 if (version_string.empty ())
1388 str = version_string.c_str ();
1389 if (str == NULL || *str == '\0')
1392 version = strtoul (str, &end, 10);
1394 INTERNAL_ERROR ("Malformed database version: %s", str);
1400 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1402 unsigned int version;
1404 if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_WRITE)
1407 if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
1410 version = notmuch_database_get_version (notmuch);
1412 return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
1415 static volatile sig_atomic_t do_progress_notify = 0;
1418 handle_sigalrm (unused (int signal))
1420 do_progress_notify = 1;
1423 /* Upgrade the current database.
1425 * After opening a database in read-write mode, the client should
1426 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1427 * if so, upgrade with this function before making any modifications.
1429 * The optional progress_notify callback can be used by the caller to
1430 * provide progress indication to the user. If non-NULL it will be
1431 * called periodically with 'count' as the number of messages upgraded
1432 * so far and 'total' the overall number of messages that will be
1436 notmuch_database_upgrade (notmuch_database_t *notmuch,
1437 void (*progress_notify) (void *closure,
1441 void *local = talloc_new (NULL);
1442 Xapian::TermIterator t, t_end;
1443 Xapian::WritableDatabase *db;
1444 struct sigaction action;
1445 struct itimerval timerval;
1446 bool timer_is_active = false;
1447 enum _notmuch_features target_features, new_features;
1448 notmuch_status_t status;
1449 notmuch_private_status_t private_status;
1450 notmuch_query_t *query = NULL;
1451 unsigned int count = 0, total = 0;
1453 status = _notmuch_database_ensure_writable (notmuch);
1457 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1459 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1460 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1462 if (! notmuch_database_needs_upgrade (notmuch))
1463 return NOTMUCH_STATUS_SUCCESS;
1465 if (progress_notify) {
1466 /* Set up our handler for SIGALRM */
1467 memset (&action, 0, sizeof (struct sigaction));
1468 action.sa_handler = handle_sigalrm;
1469 sigemptyset (&action.sa_mask);
1470 action.sa_flags = SA_RESTART;
1471 sigaction (SIGALRM, &action, NULL);
1473 /* Then start a timer to send SIGALRM once per second. */
1474 timerval.it_interval.tv_sec = 1;
1475 timerval.it_interval.tv_usec = 0;
1476 timerval.it_value.tv_sec = 1;
1477 timerval.it_value.tv_usec = 0;
1478 setitimer (ITIMER_REAL, &timerval, NULL);
1480 timer_is_active = true;
1483 /* Figure out how much total work we need to do. */
1485 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1486 NOTMUCH_FEATURE_LAST_MOD)) {
1487 query = notmuch_query_create (notmuch, "");
1490 status = notmuch_query_count_messages (query, &msg_count);
1495 notmuch_query_destroy (query);
1498 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1499 t_end = db->allterms_end ("XTIMESTAMP");
1500 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1503 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1504 /* The ghost message upgrade converts all thread_id_*
1505 * metadata values into ghost message documents. */
1506 t_end = db->metadata_keys_end ("thread_id_");
1507 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1511 /* Perform the upgrade in a transaction. */
1512 db->begin_transaction (true);
1514 /* Set the target features so we write out changes in the desired
1516 notmuch->features = target_features;
1518 /* Perform per-message upgrades. */
1520 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1521 NOTMUCH_FEATURE_LAST_MOD)) {
1522 notmuch_messages_t *messages;
1523 notmuch_message_t *message;
1526 query = notmuch_query_create (notmuch, "");
1528 status = notmuch_query_search_messages (query, &messages);
1532 notmuch_messages_valid (messages);
1533 notmuch_messages_move_to_next (messages)) {
1534 if (do_progress_notify) {
1535 progress_notify (closure, (double) count / total);
1536 do_progress_notify = 0;
1539 message = notmuch_messages_get (messages);
1541 /* Before version 1, each message document had its
1542 * filename in the data field. Copy that into the new
1543 * format by calling notmuch_message_add_filename.
1545 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1546 filename = _notmuch_message_talloc_copy_data (message);
1547 if (filename && *filename != '\0') {
1548 _notmuch_message_add_filename (message, filename);
1549 _notmuch_message_clear_data (message);
1551 talloc_free (filename);
1554 /* Prior to version 2, the "folder:" prefix was
1555 * probabilistic and stemmed. Change it to the current
1556 * boolean prefix. Add "path:" prefixes while at it.
1558 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1559 _notmuch_message_upgrade_folder (message);
1561 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1562 * track modification revisions. Give all messages the
1563 * next available revision; since we just started tracking
1564 * revisions for this database, that will be 1.
1566 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1567 _notmuch_message_upgrade_last_mod (message);
1569 _notmuch_message_sync (message);
1571 notmuch_message_destroy (message);
1576 notmuch_query_destroy (query);
1580 /* Perform per-directory upgrades. */
1582 /* Before version 1 we stored directory timestamps in
1583 * XTIMESTAMP documents instead of the current XDIRECTORY
1584 * documents. So copy those as well. */
1585 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1586 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1588 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1591 Xapian::PostingIterator p, p_end;
1592 std::string term = *t;
1594 p_end = notmuch->xapian_db->postlist_end (term);
1596 for (p = notmuch->xapian_db->postlist_begin (term);
1599 Xapian::Document document;
1601 notmuch_directory_t *directory;
1603 if (do_progress_notify) {
1604 progress_notify (closure, (double) count / total);
1605 do_progress_notify = 0;
1608 document = find_document_for_doc_id (notmuch, *p);
1609 mtime = Xapian::sortable_unserialise (
1610 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1612 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1613 NOTMUCH_FIND_CREATE, &status);
1614 notmuch_directory_set_mtime (directory, mtime);
1615 notmuch_directory_destroy (directory);
1617 db->delete_document (*p);
1624 /* Perform metadata upgrades. */
1626 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1627 * messages were stored as database metadata. Change these to
1630 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1631 notmuch_message_t *message;
1632 std::string message_id, thread_id;
1634 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1635 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1637 if (do_progress_notify) {
1638 progress_notify (closure, (double) count / total);
1639 do_progress_notify = 0;
1642 message_id = (*t).substr (
1643 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1644 thread_id = db->get_metadata (*t);
1646 /* Create ghost message */
1647 message = _notmuch_message_create_for_message_id (
1648 notmuch, message_id.c_str (), &private_status);
1649 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1650 /* Document already exists; ignore the stored thread ID */
1651 } else if (private_status ==
1652 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1653 private_status = _notmuch_message_initialize_ghost (
1654 message, thread_id.c_str ());
1655 if (! private_status)
1656 _notmuch_message_sync (message);
1659 if (private_status) {
1660 _notmuch_database_log (notmuch,
1661 "Upgrade failed while creating ghost messages.\n");
1662 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1666 /* Clear saved metadata thread ID */
1667 db->set_metadata (*t, "");
1673 status = NOTMUCH_STATUS_SUCCESS;
1674 db->set_metadata ("features", _print_features (local, notmuch->features));
1675 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1678 if (status == NOTMUCH_STATUS_SUCCESS)
1679 db->commit_transaction ();
1681 db->cancel_transaction ();
1683 if (timer_is_active) {
1684 /* Now stop the timer. */
1685 timerval.it_interval.tv_sec = 0;
1686 timerval.it_interval.tv_usec = 0;
1687 timerval.it_value.tv_sec = 0;
1688 timerval.it_value.tv_usec = 0;
1689 setitimer (ITIMER_REAL, &timerval, NULL);
1691 /* And disable the signal handler. */
1692 action.sa_handler = SIG_IGN;
1693 sigaction (SIGALRM, &action, NULL);
1697 notmuch_query_destroy (query);
1699 talloc_free (local);
1704 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1706 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1707 notmuch->atomic_nesting > 0)
1710 if (notmuch_database_needs_upgrade (notmuch))
1711 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1714 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1715 } catch (const Xapian::Error &error) {
1716 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1717 error.get_msg ().c_str ());
1718 notmuch->exception_reported = true;
1719 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1723 notmuch->atomic_nesting++;
1724 return NOTMUCH_STATUS_SUCCESS;
1728 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1730 Xapian::WritableDatabase *db;
1732 if (notmuch->atomic_nesting == 0)
1733 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1735 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1736 notmuch->atomic_nesting > 1)
1739 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1741 db->commit_transaction ();
1743 /* This is a hack for testing. Xapian never flushes on a
1744 * non-flushed commit, even if the flush threshold is 1.
1745 * However, we rely on flushing to test atomicity. */
1746 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1747 if (thresh && atoi (thresh) == 1)
1749 } catch (const Xapian::Error &error) {
1750 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1751 error.get_msg ().c_str ());
1752 notmuch->exception_reported = true;
1753 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1756 if (notmuch->atomic_dirty) {
1757 ++notmuch->revision;
1758 notmuch->atomic_dirty = false;
1762 notmuch->atomic_nesting--;
1763 return NOTMUCH_STATUS_SUCCESS;
1767 notmuch_database_get_revision (notmuch_database_t *notmuch,
1771 *uuid = notmuch->uuid;
1772 return notmuch->revision;
1775 /* We allow the user to use arbitrarily long paths for directories. But
1776 * we have a term-length limit. So if we exceed that, we'll use the
1777 * SHA-1 of the path for the database term.
1779 * Note: This function may return the original value of 'path'. If it
1780 * does not, then the caller is responsible to free() the returned
1784 _notmuch_database_get_directory_db_path (const char *path)
1786 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1788 if (term_len > NOTMUCH_TERM_MAX)
1789 return _notmuch_sha1_of_string (path);
1794 /* Given a path, split it into two parts: the directory part is all
1795 * components except for the last, and the basename is that last
1796 * component. Getting the return-value for either part is optional
1797 * (the caller can pass NULL).
1799 * The original 'path' can represent either a regular file or a
1800 * directory---the splitting will be carried out in the same way in
1801 * either case. Trailing slashes on 'path' will be ignored, and any
1802 * cases of multiple '/' characters appearing in series will be
1803 * treated as a single '/'.
1805 * Allocation (if any) will have 'ctx' as the talloc owner. But
1806 * pointers will be returned within the original path string whenever
1809 * Note: If 'path' is non-empty and contains no non-trailing slash,
1810 * (that is, consists of a filename with no parent directory), then
1811 * the directory returned will be an empty string. However, if 'path'
1812 * is an empty string, then both directory and basename will be
1816 _notmuch_database_split_path (void *ctx,
1818 const char **directory,
1819 const char **basename)
1823 if (path == NULL || *path == '\0') {
1828 return NOTMUCH_STATUS_SUCCESS;
1831 /* Find the last slash (not counting a trailing slash), if any. */
1833 slash = path + strlen (path) - 1;
1835 /* First, skip trailing slashes. */
1836 while (slash != path && *slash == '/')
1839 /* Then, find a slash. */
1840 while (slash != path && *slash != '/') {
1847 /* Finally, skip multiple slashes. */
1848 while (slash != path && *(slash - 1) == '/')
1851 if (slash == path) {
1853 *directory = talloc_strdup (ctx, "");
1858 *directory = talloc_strndup (ctx, path, slash - path);
1861 return NOTMUCH_STATUS_SUCCESS;
1864 /* Find the document ID of the specified directory.
1866 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1867 * created if one does not exist for 'path'. Otherwise, if the
1868 * directory document does not exist, this sets *directory_id to
1869 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1872 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1874 notmuch_find_flags_t flags,
1875 unsigned int *directory_id)
1877 notmuch_directory_t *directory;
1878 notmuch_status_t status;
1882 return NOTMUCH_STATUS_SUCCESS;
1885 directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1886 if (status || ! directory) {
1891 *directory_id = _notmuch_directory_get_document_id (directory);
1893 notmuch_directory_destroy (directory);
1895 return NOTMUCH_STATUS_SUCCESS;
1899 _notmuch_database_get_directory_path (void *ctx,
1900 notmuch_database_t *notmuch,
1901 unsigned int doc_id)
1903 Xapian::Document document;
1905 document = find_document_for_doc_id (notmuch, doc_id);
1907 return talloc_strdup (ctx, document.get_data ().c_str ());
1910 /* Given a legal 'filename' for the database, (either relative to
1911 * database path or absolute with initial components identical to
1912 * database path), return a new string (with 'ctx' as the talloc
1913 * owner) suitable for use as a direntry term value.
1915 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1916 * will be created in the database as needed. Otherwise, if the
1917 * necessary directory documents do not exist, this sets
1918 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1921 _notmuch_database_filename_to_direntry (void *ctx,
1922 notmuch_database_t *notmuch,
1923 const char *filename,
1924 notmuch_find_flags_t flags,
1927 const char *relative, *directory, *basename;
1928 Xapian::docid directory_id;
1929 notmuch_status_t status;
1931 relative = _notmuch_database_relative_path (notmuch, filename);
1933 status = _notmuch_database_split_path (ctx, relative,
1934 &directory, &basename);
1938 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1940 if (status || directory_id == (unsigned int) -1) {
1945 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1947 return NOTMUCH_STATUS_SUCCESS;
1950 /* Given a legal 'path' for the database, return the relative path.
1952 * The return value will be a pointer to the original path contents,
1953 * and will be either the original string (if 'path' was relative) or
1954 * a portion of the string (if path was absolute and begins with the
1958 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1961 const char *db_path, *relative;
1962 unsigned int db_path_len;
1964 db_path = notmuch_database_get_path (notmuch);
1965 db_path_len = strlen (db_path);
1969 if (*relative == '/') {
1970 while (*relative == '/' && *(relative + 1) == '/')
1973 if (strncmp (relative, db_path, db_path_len) == 0) {
1974 relative += db_path_len;
1975 while (*relative == '/')
1984 notmuch_database_get_directory (notmuch_database_t *notmuch,
1986 notmuch_directory_t **directory)
1988 notmuch_status_t status;
1990 if (directory == NULL)
1991 return NOTMUCH_STATUS_NULL_POINTER;
1995 *directory = _notmuch_directory_find_or_create (notmuch, path,
1996 NOTMUCH_FIND_LOOKUP, &status);
1997 } catch (const Xapian::Error &error) {
1998 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1999 error.get_msg ().c_str ());
2000 notmuch->exception_reported = true;
2001 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2006 /* Allocate a document ID that satisfies the following criteria:
2008 * 1. The ID does not exist for any document in the Xapian database
2010 * 2. The ID was not previously returned from this function
2012 * 3. The ID is the smallest integer satisfying (1) and (2)
2014 * This function will trigger an internal error if these constraints
2015 * cannot all be satisfied, (that is, the pool of available document
2016 * IDs has been exhausted).
2019 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2021 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2023 notmuch->last_doc_id++;
2025 if (notmuch->last_doc_id == 0)
2026 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2028 return notmuch->last_doc_id;
2032 notmuch_database_remove_message (notmuch_database_t *notmuch,
2033 const char *filename)
2035 notmuch_status_t status;
2036 notmuch_message_t *message;
2038 status = notmuch_database_find_message_by_filename (notmuch, filename,
2041 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2042 status = _notmuch_message_remove_filename (message, filename);
2043 if (status == NOTMUCH_STATUS_SUCCESS)
2044 _notmuch_message_delete (message);
2045 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2046 _notmuch_message_sync (message);
2048 notmuch_message_destroy (message);
2055 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2056 const char *filename,
2057 notmuch_message_t **message_ret)
2060 const char *prefix = _find_prefix ("file-direntry");
2061 char *direntry, *term;
2062 Xapian::PostingIterator i, end;
2063 notmuch_status_t status;
2065 if (message_ret == NULL)
2066 return NOTMUCH_STATUS_NULL_POINTER;
2068 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2069 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2071 /* return NULL on any failure */
2072 *message_ret = NULL;
2074 local = talloc_new (notmuch);
2077 status = _notmuch_database_filename_to_direntry (
2078 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2079 if (status || ! direntry)
2082 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2084 find_doc_ids_for_term (notmuch, term, &i, &end);
2087 notmuch_private_status_t private_status;
2089 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2091 if (*message_ret == NULL)
2092 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2094 } catch (const Xapian::Error &error) {
2095 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2096 error.get_msg ().c_str ());
2097 notmuch->exception_reported = true;
2098 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2102 talloc_free (local);
2104 if (status && *message_ret) {
2105 notmuch_message_destroy (*message_ret);
2106 *message_ret = NULL;
2111 notmuch_string_list_t *
2112 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2113 Xapian::TermIterator &end,
2116 int prefix_len = strlen (prefix);
2117 notmuch_string_list_t *list;
2119 list = _notmuch_string_list_create (ctx);
2120 if (unlikely (list == NULL))
2123 for (i.skip_to (prefix); i != end; i++) {
2124 /* Terminate loop at first term without desired prefix. */
2125 if (strncmp ((*i).c_str (), prefix, prefix_len))
2128 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2135 notmuch_database_get_all_tags (notmuch_database_t *db)
2137 Xapian::TermIterator i, end;
2138 notmuch_string_list_t *tags;
2141 i = db->xapian_db->allterms_begin ();
2142 end = db->xapian_db->allterms_end ();
2143 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2144 _find_prefix ("tag"));
2145 _notmuch_string_list_sort (tags);
2146 return _notmuch_tags_create (db, tags);
2147 } catch (const Xapian::Error &error) {
2148 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2149 error.get_msg ().c_str ());
2150 db->exception_reported = true;
2156 notmuch_database_status_string (const notmuch_database_t *notmuch)
2158 return notmuch->status_string;