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 "string-util.h"
31 #include <glib.h> /* g_free, GPtrArray, GHashTable */
32 #include <glib-object.h> /* g_type_init */
34 #include <gmime/gmime.h> /* g_mime_init */
41 notmuch_field_flag_t flags;
44 #define NOTMUCH_DATABASE_VERSION 3
46 #define STRINGIFY(s) _SUB_STRINGIFY (s)
47 #define _SUB_STRINGIFY(s) #s
49 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
52 _log_xapian_exception (const char *where, notmuch_database_t *notmuch, const Xapian::Error error)
54 _notmuch_database_log (notmuch,
55 "A Xapian exception occurred at %s: %s\n",
57 error.get_msg ().c_str ());
58 notmuch->exception_reported = true;
61 notmuch_database_mode_t
62 _notmuch_database_mode (notmuch_database_t *notmuch)
64 if (notmuch->writable_xapian_db)
65 return NOTMUCH_DATABASE_MODE_READ_WRITE;
67 return NOTMUCH_DATABASE_MODE_READ_ONLY;
70 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
72 * We currently have three different types of documents (mail, ghost,
73 * and directory) and also some metadata.
75 * There are two kinds of prefixes used in notmuch. There are the
76 * human friendly 'prefix names' like "thread:", which are also used
77 * in the query parser, and the actual prefix terms in the database
78 * (e.g. "G"). The correspondence is maintained in the file scope data
79 * structure 'prefix_table'.
83 * A mail document is associated with a particular email message. It
84 * is stored in one or more files on disk and is uniquely identified
85 * by its "id" field (which is generally the message ID). It is
86 * indexed with the following prefixed terms which the database uses
87 * to construct threads, etc.:
89 * Single terms of given prefix:
93 * id: Unique ID of mail. This is from the Message-ID header
94 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
95 * If it's present and too long, then we use
96 * "notmuch-sha1-<sha1_sum_of_message_id>".
97 * If this header is not present, we use
98 * "notmuch-sha1-<sha1_sum_of_entire_file>".
100 * thread: The ID of the thread to which the mail belongs
102 * replyto: The ID from the In-Reply-To header of the mail (if any).
104 * Multiple terms of given prefix:
106 * reference: All message IDs from In-Reply-To and References
107 * headers in the message.
109 * tag: Any tags associated with this message by the user.
111 * file-direntry: A colon-separated pair of values
112 * (INTEGER:STRING), where INTEGER is the
113 * document ID of a directory document, and
114 * STRING is the name of a file within that
115 * directory for this mail message.
117 * property: Has a property with key=value
118 * FIXME: if no = is present, should match on any value
120 * A mail document also has four values:
122 * TIMESTAMP: The time_t value corresponding to the message's
125 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
127 * FROM: The value of the "From" header
129 * SUBJECT: The value of the "Subject" header
131 * LAST_MOD: The revision number as of the last tag or
134 * The prefixed terms described above are also searchable without an
135 * explicit field name, but as of notmuch 0.29 this is due to
136 * query-parser setup, not extra terms in the database. In addition,
137 * terms from the content of the message are added without a prefix
138 * for use by the user in searching. Note that the prefix name "body"
139 * is used to refer to the empty prefix string in the database.
141 * The path of the containing folder is added with the "folder" prefix
142 * (see _notmuch_message_add_folder_terms). Sub-paths of the the path
143 * of the mail message are added with the "path" prefix.
145 * The data portion of a mail document is empty.
147 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
148 * -----------------------------------------------
149 * A ghost mail document is like a mail document, but where we don't
150 * have the message content. These are used to track thread reference
151 * information for messages we haven't received.
153 * A ghost mail document has type: ghost; id and thread fields that
154 * are identical to the mail document fields; and a MESSAGE_ID value.
158 * A directory document is used by a client of the notmuch library to
159 * maintain data necessary to allow for efficient polling of mail
162 * All directory documents contain one term:
164 * directory: The directory path (relative to the database path)
165 * Or the SHA1 sum of the directory path (if the
166 * path itself is too long to fit in a Xapian
169 * And all directory documents for directories other than top-level
170 * directories also contain the following term:
172 * directory-direntry: A colon-separated pair of values
173 * (INTEGER:STRING), where INTEGER is the
174 * document ID of the parent directory
175 * document, and STRING is the name of this
176 * directory within that parent.
178 * All directory documents have a single value:
180 * TIMESTAMP: The mtime of the directory (at last scan)
182 * The data portion of a directory document contains the path of the
183 * directory (relative to the database path).
187 * Xapian allows us to store arbitrary name-value pairs as
188 * "metadata". We currently use the following metadata names with the
191 * version The database schema version, (which is distinct
192 * from both the notmuch package version (see
193 * notmuch --version) and the libnotmuch library
194 * version. The version is stored as an base-10
195 * ASCII integer. The initial database version
196 * was 1, (though a schema existed before that
197 * were no "version" database value existed at
198 * all). Successive versions are allocated as
199 * changes are made to the database (such as by
200 * indexing new fields).
202 * features The set of features supported by this
203 * database. This consists of a set of
204 * '\n'-separated lines, where each is a feature
205 * name, a '\t', and compatibility flags. If the
206 * compatibility flags contain 'w', then the
207 * opener must support this feature to safely
208 * write this database. If the compatibility
209 * flags contain 'r', then the opener must
210 * support this feature to read this database.
211 * Introduced in database version 3.
213 * last_thread_id The last thread ID generated. This is stored
214 * as a 16-byte hexadecimal ASCII representation
215 * of a 64-bit unsigned integer. The first ID
216 * generated is 1 and the value will be
217 * incremented for each thread ID.
219 * C* metadata keys starting with C indicate
220 * configuration data. It can be managed with the
221 * n_database_*config* API. There is a convention
222 * of hierarchical keys separated by '.' (e.g.
223 * query.notmuch stores the value for the named
224 * query 'notmuch'), but it is not enforced by the
230 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
231 * Instead, the database has the following additional database
234 * thread_id_* A pre-allocated thread ID for a particular
235 * message. This is actually an arbitrarily large
236 * family of metadata name. Any particular name is
237 * formed by concatenating "thread_id_" with a message
238 * ID (or the SHA1 sum of a message ID if it is very
239 * long---see description of 'id' in the mail
240 * document). The value stored is a thread ID.
242 * These thread ID metadata values are stored
243 * whenever a message references a parent message
244 * that does not yet exist in the database. A
245 * thread ID will be allocated and stored, and if
246 * the message is later added, the stored thread
247 * ID will be used (and the metadata value will
250 * Even before a message is added, it's
251 * pre-allocated thread ID is useful so that all
252 * descendant messages that reference this common
253 * parent can be recognized as belonging to the
258 notmuch_string_map_iterator_t *
259 _notmuch_database_user_headers (notmuch_database_t *notmuch)
261 return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
265 notmuch_status_to_string (notmuch_status_t status)
268 case NOTMUCH_STATUS_SUCCESS:
269 return "No error occurred";
270 case NOTMUCH_STATUS_OUT_OF_MEMORY:
271 return "Out of memory";
272 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
273 return "Attempt to write to a read-only database";
274 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
275 return "A Xapian exception occurred";
276 case NOTMUCH_STATUS_FILE_ERROR:
277 return "Something went wrong trying to read or write a file";
278 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
279 return "File is not an email";
280 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
281 return "Message ID is identical to a message in database";
282 case NOTMUCH_STATUS_NULL_POINTER:
283 return "Erroneous NULL pointer";
284 case NOTMUCH_STATUS_TAG_TOO_LONG:
285 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
286 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
287 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
288 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
289 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
290 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
291 return "Unsupported operation";
292 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
293 return "Operation requires a database upgrade";
294 case NOTMUCH_STATUS_PATH_ERROR:
295 return "Path supplied is illegal for this function";
296 case NOTMUCH_STATUS_IGNORED:
297 return "Argument was ignored";
298 case NOTMUCH_STATUS_ILLEGAL_ARGUMENT:
299 return "Illegal argument for function";
300 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
301 return "Crypto protocol missing, malformed, or unintelligible";
302 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
303 return "Crypto engine initialization failure";
304 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
305 return "Unknown crypto protocol";
306 case NOTMUCH_STATUS_NO_CONFIG:
307 return "No configuration file found";
308 case NOTMUCH_STATUS_NO_DATABASE:
309 return "No database found";
310 case NOTMUCH_STATUS_DATABASE_EXISTS:
311 return "Database exists, not recreated";
312 case NOTMUCH_STATUS_BAD_QUERY_SYNTAX:
313 return "Syntax error in query";
314 case NOTMUCH_STATUS_NO_MAIL_ROOT:
315 return "No mail root found";
317 case NOTMUCH_STATUS_LAST_STATUS:
318 return "Unknown error status value";
323 _notmuch_database_log (notmuch_database_t *notmuch,
329 va_start (va_args, format);
331 if (notmuch->status_string)
332 talloc_free (notmuch->status_string);
334 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
339 _notmuch_database_log_append (notmuch_database_t *notmuch,
345 va_start (va_args, format);
347 if (notmuch->status_string)
348 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
350 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
356 find_doc_ids_for_term (notmuch_database_t *notmuch,
358 Xapian::PostingIterator *begin,
359 Xapian::PostingIterator *end)
361 *begin = notmuch->xapian_db->postlist_begin (term);
363 *end = notmuch->xapian_db->postlist_end (term);
367 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
368 const char *prefix_name,
370 Xapian::PostingIterator *begin,
371 Xapian::PostingIterator *end)
375 term = talloc_asprintf (notmuch, "%s%s",
376 _find_prefix (prefix_name), value);
378 find_doc_ids_for_term (notmuch, term, begin, end);
383 notmuch_private_status_t
384 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
385 const char *prefix_name,
387 unsigned int *doc_id)
389 Xapian::PostingIterator i, end;
391 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
395 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
400 #if DEBUG_DATABASE_SANITY
404 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
408 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
411 static Xapian::Document
412 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
414 return notmuch->xapian_db->get_document (doc_id);
417 /* Generate a compressed version of 'message_id' of the form:
419 * notmuch-sha1-<sha1_sum_of_message_id>
422 _notmuch_message_id_compressed (void *ctx, const char *message_id)
424 char *sha1, *compressed;
426 sha1 = _notmuch_sha1_of_string (message_id);
428 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
435 notmuch_database_find_message (notmuch_database_t *notmuch,
436 const char *message_id,
437 notmuch_message_t **message_ret)
439 notmuch_private_status_t status;
442 if (message_ret == NULL)
443 return NOTMUCH_STATUS_NULL_POINTER;
445 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
446 message_id = _notmuch_message_id_compressed (notmuch, message_id);
449 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
450 message_id, &doc_id);
452 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
455 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
457 if (*message_ret == NULL)
458 return NOTMUCH_STATUS_OUT_OF_MEMORY;
461 return NOTMUCH_STATUS_SUCCESS;
462 } catch (const Xapian::Error &error) {
463 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
464 error.get_msg ().c_str ());
465 notmuch->exception_reported = true;
467 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
472 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
474 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY) {
475 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
476 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
479 return NOTMUCH_STATUS_SUCCESS;
482 /* Allocate a revision number for the next change. */
484 _notmuch_database_new_revision (notmuch_database_t *notmuch)
486 unsigned long new_revision = notmuch->revision + 1;
488 /* If we're in an atomic section, hold off on updating the
489 * committed revision number until we commit the atomic section.
491 if (notmuch->atomic_nesting)
492 notmuch->atomic_dirty = true;
494 notmuch->revision = new_revision;
500 notmuch_database_close (notmuch_database_t *notmuch)
502 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
504 /* Many Xapian objects (and thus notmuch objects) hold references to
505 * the database, so merely deleting the database may not suffice to
506 * close it. Thus, we explicitly close it here. */
509 /* Close the database. This implicitly flushes
510 * outstanding changes. If there is an open (non-flushed)
511 * transaction, ALL pending changes will be discarded */
512 notmuch->xapian_db->close ();
513 } catch (const Xapian::Error &error) {
514 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
515 if (! notmuch->exception_reported) {
516 _notmuch_database_log (notmuch,
517 "Error: A Xapian exception occurred closing database: %s\n",
518 error.get_msg ().c_str ());
522 notmuch->open = false;
527 unlink_cb (const char *path,
528 unused (const struct stat *sb),
530 unused (struct FTW *ftw))
532 return remove (path);
536 rmtree (const char *path)
538 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
541 class NotmuchCompactor : public Xapian::Compactor
543 notmuch_compact_status_cb_t status_cb;
544 void *status_closure;
547 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
548 status_cb (cb), status_closure (closure)
553 set_status (const std::string &table, const std::string &status)
557 if (status_cb == NULL)
560 if (status.length () == 0)
561 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
563 msg = talloc_asprintf (NULL, " %s", status.c_str ());
569 status_cb (msg, status_closure);
574 /* Compacts the given database, optionally saving the original database
575 * in backup_path. Additionally, a callback function can be provided to
576 * give the user feedback on the progress of the (likely long-lived)
577 * compaction process.
579 * The backup path must point to a directory on the same volume as the
580 * original database. Passing a NULL backup_path will result in the
581 * uncompacted database being deleted after compaction has finished.
582 * Note that the database write lock will be held during the
583 * compaction process to protect data integrity.
586 notmuch_database_compact (const char *path,
587 const char *backup_path,
588 notmuch_compact_status_cb_t status_cb,
591 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
592 notmuch_database_t *notmuch = NULL;
593 char *message = NULL;
595 ret = notmuch_database_open_with_config (path,
596 NOTMUCH_DATABASE_MODE_READ_WRITE,
602 if (status_cb) status_cb (message, closure);
606 _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
608 return notmuch_database_compact_db (notmuch,
615 notmuch_database_compact_db (notmuch_database_t *notmuch,
616 const char *backup_path,
617 notmuch_compact_status_cb_t status_cb,
621 const char *xapian_path, *compact_xapian_path;
623 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
628 ret = _notmuch_database_ensure_writable (notmuch);
632 path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
634 return NOTMUCH_STATUS_PATH_ERROR;
636 local = talloc_new (NULL);
638 return NOTMUCH_STATUS_OUT_OF_MEMORY;
640 ret = _notmuch_choose_xapian_path (local, path, &xapian_path, &message);
644 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
645 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
649 if (backup_path == NULL) {
650 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
651 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
659 if (stat (backup_path, &statbuf) != -1) {
660 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
661 ret = NOTMUCH_STATUS_FILE_ERROR;
664 if (errno != ENOENT) {
665 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
667 ret = NOTMUCH_STATUS_FILE_ERROR;
671 /* Unconditionally attempt to remove old work-in-progress database (if
672 * any). This is "protected" by database lock. If this fails due to write
673 * errors (etc), the following code will fail and provide error message.
675 (void) rmtree (compact_xapian_path);
678 NotmuchCompactor compactor (status_cb, closure);
679 notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0,
681 } catch (const Xapian::Error &error) {
682 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
683 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
687 if (rename (xapian_path, backup_path)) {
688 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
689 xapian_path, backup_path, strerror (errno));
690 ret = NOTMUCH_STATUS_FILE_ERROR;
694 if (rename (compact_xapian_path, xapian_path)) {
695 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
696 compact_xapian_path, xapian_path, strerror (errno));
697 ret = NOTMUCH_STATUS_FILE_ERROR;
702 if (rmtree (backup_path)) {
703 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
704 backup_path, strerror (errno));
705 ret = NOTMUCH_STATUS_FILE_ERROR;
712 notmuch_status_t ret2;
714 const char *str = notmuch_database_status_string (notmuch);
715 if (status_cb && str)
716 status_cb (str, closure);
718 ret2 = notmuch_database_destroy (notmuch);
720 /* don't clobber previous error status */
721 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
731 notmuch_database_destroy (notmuch_database_t *notmuch)
733 notmuch_status_t status;
734 const char *talloc_report;
736 talloc_report = getenv ("NOTMUCH_TALLOC_REPORT");
737 if (talloc_report && strcmp (talloc_report, "") != 0) {
738 FILE *report = fopen (talloc_report, "a");
740 talloc_report_full (notmuch, report);
744 status = notmuch_database_close (notmuch);
746 delete notmuch->term_gen;
747 notmuch->term_gen = NULL;
748 delete notmuch->query_parser;
749 notmuch->query_parser = NULL;
750 delete notmuch->xapian_db;
751 notmuch->xapian_db = NULL;
752 delete notmuch->value_range_processor;
753 notmuch->value_range_processor = NULL;
754 delete notmuch->date_range_processor;
755 notmuch->date_range_processor = NULL;
756 delete notmuch->last_mod_range_processor;
757 notmuch->last_mod_range_processor = NULL;
759 talloc_free (notmuch);
765 notmuch_database_get_path (notmuch_database_t *notmuch)
767 return notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
771 notmuch_database_get_version (notmuch_database_t *notmuch)
773 unsigned int version;
774 string version_string;
779 version_string = notmuch->xapian_db->get_metadata ("version");
780 } catch (const Xapian::Error &error) {
781 LOG_XAPIAN_EXCEPTION (notmuch, error);
785 if (version_string.empty ())
788 str = version_string.c_str ();
789 if (str == NULL || *str == '\0')
792 version = strtoul (str, &end, 10);
794 INTERNAL_ERROR ("Malformed database version: %s", str);
800 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
802 unsigned int version;
804 if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_WRITE)
807 if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
810 version = notmuch_database_get_version (notmuch);
812 return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
815 static volatile sig_atomic_t do_progress_notify = 0;
818 handle_sigalrm (unused (int signal))
820 do_progress_notify = 1;
823 /* Upgrade the current database.
825 * After opening a database in read-write mode, the client should
826 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
827 * if so, upgrade with this function before making any modifications.
829 * The optional progress_notify callback can be used by the caller to
830 * provide progress indication to the user. If non-NULL it will be
831 * called periodically with 'count' as the number of messages upgraded
832 * so far and 'total' the overall number of messages that will be
836 notmuch_database_upgrade (notmuch_database_t *notmuch,
837 void (*progress_notify)(void *closure,
841 void *local = talloc_new (NULL);
842 Xapian::TermIterator t, t_end;
843 Xapian::WritableDatabase *db;
844 struct sigaction action;
845 struct itimerval timerval;
846 bool timer_is_active = false;
847 enum _notmuch_features target_features, new_features;
848 notmuch_status_t status;
849 notmuch_private_status_t private_status;
850 notmuch_query_t *query = NULL;
851 unsigned int count = 0, total = 0;
853 status = _notmuch_database_ensure_writable (notmuch);
857 db = notmuch->writable_xapian_db;
859 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
860 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
862 if (! notmuch_database_needs_upgrade (notmuch))
863 return NOTMUCH_STATUS_SUCCESS;
865 if (progress_notify) {
866 /* Set up our handler for SIGALRM */
867 memset (&action, 0, sizeof (struct sigaction));
868 action.sa_handler = handle_sigalrm;
869 sigemptyset (&action.sa_mask);
870 action.sa_flags = SA_RESTART;
871 sigaction (SIGALRM, &action, NULL);
873 /* Then start a timer to send SIGALRM once per second. */
874 timerval.it_interval.tv_sec = 1;
875 timerval.it_interval.tv_usec = 0;
876 timerval.it_value.tv_sec = 1;
877 timerval.it_value.tv_usec = 0;
878 setitimer (ITIMER_REAL, &timerval, NULL);
880 timer_is_active = true;
883 /* Figure out how much total work we need to do. */
885 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
886 NOTMUCH_FEATURE_LAST_MOD)) {
887 query = notmuch_query_create (notmuch, "");
890 status = notmuch_query_count_messages (query, &msg_count);
895 notmuch_query_destroy (query);
898 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
899 t_end = db->allterms_end ("XTIMESTAMP");
900 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
903 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
904 /* The ghost message upgrade converts all thread_id_*
905 * metadata values into ghost message documents. */
906 t_end = db->metadata_keys_end ("thread_id_");
907 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
911 /* Perform the upgrade in a transaction. */
912 db->begin_transaction (true);
914 /* Set the target features so we write out changes in the desired
916 notmuch->features = target_features;
918 /* Perform per-message upgrades. */
920 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
921 NOTMUCH_FEATURE_LAST_MOD)) {
922 notmuch_messages_t *messages;
923 notmuch_message_t *message;
926 query = notmuch_query_create (notmuch, "");
928 status = notmuch_query_search_messages (query, &messages);
932 notmuch_messages_valid (messages);
933 notmuch_messages_move_to_next (messages)) {
934 if (do_progress_notify) {
935 progress_notify (closure, (double) count / total);
936 do_progress_notify = 0;
939 message = notmuch_messages_get (messages);
941 /* Before version 1, each message document had its
942 * filename in the data field. Copy that into the new
943 * format by calling notmuch_message_add_filename.
945 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
946 filename = _notmuch_message_talloc_copy_data (message);
947 if (filename && *filename != '\0') {
948 _notmuch_message_add_filename (message, filename);
949 _notmuch_message_clear_data (message);
951 talloc_free (filename);
954 /* Prior to version 2, the "folder:" prefix was
955 * probabilistic and stemmed. Change it to the current
956 * boolean prefix. Add "path:" prefixes while at it.
958 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
959 _notmuch_message_upgrade_folder (message);
961 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
962 * track modification revisions. Give all messages the
963 * next available revision; since we just started tracking
964 * revisions for this database, that will be 1.
966 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
967 _notmuch_message_upgrade_last_mod (message);
969 _notmuch_message_sync (message);
971 notmuch_message_destroy (message);
976 notmuch_query_destroy (query);
980 /* Perform per-directory upgrades. */
982 /* Before version 1 we stored directory timestamps in
983 * XTIMESTAMP documents instead of the current XDIRECTORY
984 * documents. So copy those as well. */
985 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
986 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
988 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
991 Xapian::PostingIterator p, p_end;
992 std::string term = *t;
994 p_end = notmuch->xapian_db->postlist_end (term);
996 for (p = notmuch->xapian_db->postlist_begin (term);
999 Xapian::Document document;
1001 notmuch_directory_t *directory;
1003 if (do_progress_notify) {
1004 progress_notify (closure, (double) count / total);
1005 do_progress_notify = 0;
1008 document = find_document_for_doc_id (notmuch, *p);
1009 mtime = Xapian::sortable_unserialise (
1010 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1012 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1013 NOTMUCH_FIND_CREATE, &status);
1014 notmuch_directory_set_mtime (directory, mtime);
1015 notmuch_directory_destroy (directory);
1017 db->delete_document (*p);
1024 /* Perform metadata upgrades. */
1026 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1027 * messages were stored as database metadata. Change these to
1030 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1031 notmuch_message_t *message;
1032 std::string message_id, thread_id;
1034 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1035 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1037 if (do_progress_notify) {
1038 progress_notify (closure, (double) count / total);
1039 do_progress_notify = 0;
1042 message_id = (*t).substr (
1043 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1044 thread_id = db->get_metadata (*t);
1046 /* Create ghost message */
1047 message = _notmuch_message_create_for_message_id (
1048 notmuch, message_id.c_str (), &private_status);
1049 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1050 /* Document already exists; ignore the stored thread ID */
1051 } else if (private_status ==
1052 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1053 private_status = _notmuch_message_initialize_ghost (
1054 message, thread_id.c_str ());
1055 if (! private_status)
1056 _notmuch_message_sync (message);
1059 if (private_status) {
1060 _notmuch_database_log (notmuch,
1061 "Upgrade failed while creating ghost messages.\n");
1062 status = COERCE_STATUS (private_status,
1063 "Unexpected status from _notmuch_message_initialize_ghost");
1067 /* Clear saved metadata thread ID */
1068 db->set_metadata (*t, "");
1074 status = NOTMUCH_STATUS_SUCCESS;
1075 db->set_metadata ("features", _notmuch_database_print_features (local, notmuch->features));
1076 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1079 if (status == NOTMUCH_STATUS_SUCCESS)
1080 db->commit_transaction ();
1082 db->cancel_transaction ();
1084 if (timer_is_active) {
1085 /* Now stop the timer. */
1086 timerval.it_interval.tv_sec = 0;
1087 timerval.it_interval.tv_usec = 0;
1088 timerval.it_value.tv_sec = 0;
1089 timerval.it_value.tv_usec = 0;
1090 setitimer (ITIMER_REAL, &timerval, NULL);
1092 /* And disable the signal handler. */
1093 action.sa_handler = SIG_IGN;
1094 sigaction (SIGALRM, &action, NULL);
1098 notmuch_query_destroy (query);
1100 talloc_free (local);
1105 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1107 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1108 notmuch->atomic_nesting > 0)
1111 if (notmuch_database_needs_upgrade (notmuch))
1112 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1115 notmuch->writable_xapian_db->begin_transaction (false);
1116 } catch (const Xapian::Error &error) {
1117 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1118 error.get_msg ().c_str ());
1119 notmuch->exception_reported = true;
1120 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1124 notmuch->atomic_nesting++;
1125 return NOTMUCH_STATUS_SUCCESS;
1129 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1131 Xapian::WritableDatabase *db;
1133 if (notmuch->atomic_nesting == 0)
1134 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1136 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1137 notmuch->atomic_nesting > 1)
1140 db = notmuch->writable_xapian_db;
1142 db->commit_transaction ();
1143 notmuch->transaction_count++;
1145 /* Xapian never flushes on a non-flushed commit, even if the
1146 * flush threshold is 1. However, we rely on flushing to test
1147 * atomicity. On the other hand, we can't straight replace
1148 * XAPIAN_FLUSH_THRESHOLD with our autocommit counter, because
1149 * the former also applies outside notmuch atomic
1150 * commits. Hence the follow complicated test */
1151 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1152 if ((notmuch->transaction_threshold > 0 &&
1153 notmuch->transaction_count >= notmuch->transaction_threshold) ||
1154 (thresh && atoi (thresh) == 1)) {
1156 notmuch->transaction_count = 0;
1158 } catch (const Xapian::Error &error) {
1159 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1160 error.get_msg ().c_str ());
1161 notmuch->exception_reported = true;
1162 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1165 if (notmuch->atomic_dirty) {
1166 ++notmuch->revision;
1167 notmuch->atomic_dirty = false;
1171 notmuch->atomic_nesting--;
1172 return NOTMUCH_STATUS_SUCCESS;
1176 notmuch_database_get_revision (notmuch_database_t *notmuch,
1180 *uuid = notmuch->uuid;
1181 return notmuch->revision;
1184 /* We allow the user to use arbitrarily long paths for directories. But
1185 * we have a term-length limit. So if we exceed that, we'll use the
1186 * SHA-1 of the path for the database term.
1188 * Note: This function may return the original value of 'path'. If it
1189 * does not, then the caller is responsible to free() the returned
1193 _notmuch_database_get_directory_db_path (const char *path)
1195 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1197 if (term_len > NOTMUCH_TERM_MAX)
1198 return _notmuch_sha1_of_string (path);
1203 /* Given a path, split it into two parts: the directory part is all
1204 * components except for the last, and the basename is that last
1205 * component. Getting the return-value for either part is optional
1206 * (the caller can pass NULL).
1208 * The original 'path' can represent either a regular file or a
1209 * directory---the splitting will be carried out in the same way in
1210 * either case. Trailing slashes on 'path' will be ignored, and any
1211 * cases of multiple '/' characters appearing in series will be
1212 * treated as a single '/'.
1214 * Allocation (if any) will have 'ctx' as the talloc owner. But
1215 * pointers will be returned within the original path string whenever
1218 * Note: If 'path' is non-empty and contains no non-trailing slash,
1219 * (that is, consists of a filename with no parent directory), then
1220 * the directory returned will be an empty string. However, if 'path'
1221 * is an empty string, then both directory and basename will be
1225 _notmuch_database_split_path (void *ctx,
1227 const char **directory,
1228 const char **basename)
1232 if (path == NULL || *path == '\0') {
1237 return NOTMUCH_STATUS_SUCCESS;
1240 /* Find the last slash (not counting a trailing slash), if any. */
1242 slash = path + strlen (path) - 1;
1244 /* First, skip trailing slashes. */
1245 while (slash != path && *slash == '/')
1248 /* Then, find a slash. */
1249 while (slash != path && *slash != '/') {
1256 /* Finally, skip multiple slashes. */
1257 while (slash != path && *(slash - 1) == '/')
1260 if (slash == path) {
1262 *directory = talloc_strdup (ctx, "");
1267 *directory = talloc_strndup (ctx, path, slash - path);
1270 return NOTMUCH_STATUS_SUCCESS;
1273 /* Find the document ID of the specified directory.
1275 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1276 * created if one does not exist for 'path'. Otherwise, if the
1277 * directory document does not exist, this sets *directory_id to
1278 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1281 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1283 notmuch_find_flags_t flags,
1284 unsigned int *directory_id)
1286 notmuch_directory_t *directory;
1287 notmuch_status_t status;
1291 return NOTMUCH_STATUS_SUCCESS;
1294 directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1295 if (status || ! directory) {
1300 *directory_id = _notmuch_directory_get_document_id (directory);
1302 notmuch_directory_destroy (directory);
1304 return NOTMUCH_STATUS_SUCCESS;
1308 _notmuch_database_get_directory_path (void *ctx,
1309 notmuch_database_t *notmuch,
1310 unsigned int doc_id)
1312 Xapian::Document document;
1314 document = find_document_for_doc_id (notmuch, doc_id);
1316 return talloc_strdup (ctx, document.get_data ().c_str ());
1319 /* Given a legal 'filename' for the database, (either relative to
1320 * database path or absolute with initial components identical to
1321 * database path), return a new string (with 'ctx' as the talloc
1322 * owner) suitable for use as a direntry term value.
1324 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1325 * will be created in the database as needed. Otherwise, if the
1326 * necessary directory documents do not exist, this sets
1327 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1330 _notmuch_database_filename_to_direntry (void *ctx,
1331 notmuch_database_t *notmuch,
1332 const char *filename,
1333 notmuch_find_flags_t flags,
1336 const char *relative, *directory, *basename;
1337 Xapian::docid directory_id;
1338 notmuch_status_t status;
1340 relative = _notmuch_database_relative_path (notmuch, filename);
1342 status = _notmuch_database_split_path (ctx, relative,
1343 &directory, &basename);
1347 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1349 if (status || directory_id == (unsigned int) -1) {
1354 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1356 return NOTMUCH_STATUS_SUCCESS;
1359 /* Given a legal 'path' for the database, return the relative path.
1361 * The return value will be a pointer to the original path contents,
1362 * and will be either the original string (if 'path' was relative) or
1363 * a portion of the string (if path was absolute and begins with the
1367 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1370 const char *db_path, *relative;
1371 unsigned int db_path_len;
1373 db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1374 db_path_len = strlen (db_path);
1378 if (*relative == '/') {
1379 while (*relative == '/' && *(relative + 1) == '/')
1382 if (strncmp (relative, db_path, db_path_len) == 0) {
1383 relative += db_path_len;
1384 while (*relative == '/')
1393 notmuch_database_get_directory (notmuch_database_t *notmuch,
1395 notmuch_directory_t **directory)
1397 notmuch_status_t status;
1399 if (directory == NULL)
1400 return NOTMUCH_STATUS_NULL_POINTER;
1404 *directory = _notmuch_directory_find_or_create (notmuch, path,
1405 NOTMUCH_FIND_LOOKUP, &status);
1406 } catch (const Xapian::Error &error) {
1407 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1408 error.get_msg ().c_str ());
1409 notmuch->exception_reported = true;
1410 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1415 /* Allocate a document ID that satisfies the following criteria:
1417 * 1. The ID does not exist for any document in the Xapian database
1419 * 2. The ID was not previously returned from this function
1421 * 3. The ID is the smallest integer satisfying (1) and (2)
1423 * This function will trigger an internal error if these constraints
1424 * cannot all be satisfied, (that is, the pool of available document
1425 * IDs has been exhausted).
1428 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1430 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1432 notmuch->last_doc_id++;
1434 if (notmuch->last_doc_id == 0)
1435 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1437 return notmuch->last_doc_id;
1441 notmuch_database_remove_message (notmuch_database_t *notmuch,
1442 const char *filename)
1444 notmuch_status_t status;
1445 notmuch_message_t *message;
1447 status = notmuch_database_find_message_by_filename (notmuch, filename,
1450 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1451 status = _notmuch_message_remove_filename (message, filename);
1452 if (status == NOTMUCH_STATUS_SUCCESS)
1453 _notmuch_message_delete (message);
1454 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1455 _notmuch_message_sync (message);
1457 notmuch_message_destroy (message);
1464 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1465 const char *filename,
1466 notmuch_message_t **message_ret)
1469 const char *prefix = _find_prefix ("file-direntry");
1470 char *direntry, *term;
1471 Xapian::PostingIterator i, end;
1472 notmuch_status_t status;
1474 if (message_ret == NULL)
1475 return NOTMUCH_STATUS_NULL_POINTER;
1477 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1478 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1480 /* return NULL on any failure */
1481 *message_ret = NULL;
1483 local = talloc_new (notmuch);
1486 status = _notmuch_database_filename_to_direntry (
1487 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1488 if (status || ! direntry)
1491 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1493 find_doc_ids_for_term (notmuch, term, &i, &end);
1496 notmuch_private_status_t private_status;
1498 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1500 if (*message_ret == NULL)
1501 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1503 } catch (const Xapian::Error &error) {
1504 _notmuch_database_log (notmuch,
1505 "Error: A Xapian exception occurred finding message by filename: %s\n",
1506 error.get_msg ().c_str ());
1507 notmuch->exception_reported = true;
1508 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1512 talloc_free (local);
1514 if (status && *message_ret) {
1515 notmuch_message_destroy (*message_ret);
1516 *message_ret = NULL;
1521 notmuch_string_list_t *
1522 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1523 Xapian::TermIterator &end,
1526 int prefix_len = strlen (prefix);
1527 notmuch_string_list_t *list;
1529 list = _notmuch_string_list_create (ctx);
1530 if (unlikely (list == NULL))
1533 for (i.skip_to (prefix); i != end; i++) {
1534 /* Terminate loop at first term without desired prefix. */
1535 if (strncmp ((*i).c_str (), prefix, prefix_len))
1538 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1545 notmuch_database_get_all_tags (notmuch_database_t *db)
1547 Xapian::TermIterator i, end;
1548 notmuch_string_list_t *tags;
1551 i = db->xapian_db->allterms_begin ();
1552 end = db->xapian_db->allterms_end ();
1553 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1554 _find_prefix ("tag"));
1555 _notmuch_string_list_sort (tags);
1556 return _notmuch_tags_create (db, tags);
1557 } catch (const Xapian::Error &error) {
1558 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
1559 error.get_msg ().c_str ());
1560 db->exception_reported = true;
1566 notmuch_database_status_string (const notmuch_database_t *notmuch)
1568 return notmuch->status_string;