1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "thread-fp.h"
25 #include "regexp-fields.h"
26 #include "string-util.h"
35 #include <glib.h> /* g_free, GPtrArray, GHashTable */
36 #include <glib-object.h> /* g_type_init */
38 #include <gmime/gmime.h> /* g_mime_init */
42 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
47 notmuch_field_flag_t flags;
50 #define NOTMUCH_DATABASE_VERSION 3
52 #define STRINGIFY(s) _SUB_STRINGIFY(s)
53 #define _SUB_STRINGIFY(s) #s
55 #if HAVE_XAPIAN_DB_RETRY_LOCK
56 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
58 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
61 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
63 * We currently have three different types of documents (mail, ghost,
64 * and directory) and also some metadata.
66 * There are two kinds of prefixes used in notmuch. There are the
67 * human friendly 'prefix names' like "thread:", which are also used
68 * in the query parser, and the actual prefix terms in the database
69 * (e.g. "G"). The correspondence is maintained in the file scope data
70 * structure 'prefix_table'.
74 * A mail document is associated with a particular email message. It
75 * is stored in one or more files on disk and is uniquely identified
76 * by its "id" field (which is generally the message ID). It is
77 * indexed with the following prefixed terms which the database uses
78 * to construct threads, etc.:
80 * Single terms of given prefix:
84 * id: Unique ID of mail. This is from the Message-ID header
85 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
86 * If it's present and too long, then we use
87 * "notmuch-sha1-<sha1_sum_of_message_id>".
88 * If this header is not present, we use
89 * "notmuch-sha1-<sha1_sum_of_entire_file>".
91 * thread: The ID of the thread to which the mail belongs
93 * replyto: The ID from the In-Reply-To header of the mail (if any).
95 * Multiple terms of given prefix:
97 * reference: All message IDs from In-Reply-To and References
98 * headers in the message.
100 * tag: Any tags associated with this message by the user.
102 * file-direntry: A colon-separated pair of values
103 * (INTEGER:STRING), where INTEGER is the
104 * document ID of a directory document, and
105 * STRING is the name of a file within that
106 * directory for this mail message.
108 * property: Has a property with key=value
109 * FIXME: if no = is present, should match on any value
111 * A mail document also has four values:
113 * TIMESTAMP: The time_t value corresponding to the message's
116 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
118 * FROM: The value of the "From" header
120 * SUBJECT: The value of the "Subject" header
122 * LAST_MOD: The revision number as of the last tag or
125 * In addition, terms from the content of the message are added with
126 * "from", "to", "attachment", and "subject" prefixes for use by the
129 * The path of the containing folder is added with the "folder" prefix
130 * (see _notmuch_message_add_folder_terms). Sub-paths of the the path
131 * of the mail message are added with the "path" prefix.
133 * The data portion of a mail document is empty.
135 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
136 * -----------------------------------------------
137 * A ghost mail document is like a mail document, but where we don't
138 * have the message content. These are used to track thread reference
139 * information for messages we haven't received.
141 * A ghost mail document has type: ghost; id and thread fields that
142 * are identical to the mail document fields; and a MESSAGE_ID value.
146 * A directory document is used by a client of the notmuch library to
147 * maintain data necessary to allow for efficient polling of mail
150 * All directory documents contain one term:
152 * directory: The directory path (relative to the database path)
153 * Or the SHA1 sum of the directory path (if the
154 * path itself is too long to fit in a Xapian
157 * And all directory documents for directories other than top-level
158 * directories also contain the following term:
160 * directory-direntry: A colon-separated pair of values
161 * (INTEGER:STRING), where INTEGER is the
162 * document ID of the parent directory
163 * document, and STRING is the name of this
164 * directory within that parent.
166 * All directory documents have a single value:
168 * TIMESTAMP: The mtime of the directory (at last scan)
170 * The data portion of a directory document contains the path of the
171 * directory (relative to the database path).
175 * Xapian allows us to store arbitrary name-value pairs as
176 * "metadata". We currently use the following metadata names with the
179 * version The database schema version, (which is distinct
180 * from both the notmuch package version (see
181 * notmuch --version) and the libnotmuch library
182 * version. The version is stored as an base-10
183 * ASCII integer. The initial database version
184 * was 1, (though a schema existed before that
185 * were no "version" database value existed at
186 * all). Successive versions are allocated as
187 * changes are made to the database (such as by
188 * indexing new fields).
190 * features The set of features supported by this
191 * database. This consists of a set of
192 * '\n'-separated lines, where each is a feature
193 * name, a '\t', and compatibility flags. If the
194 * compatibility flags contain 'w', then the
195 * opener must support this feature to safely
196 * write this database. If the compatibility
197 * flags contain 'r', then the opener must
198 * support this feature to read this database.
199 * Introduced in database version 3.
201 * last_thread_id The last thread ID generated. This is stored
202 * as a 16-byte hexadecimal ASCII representation
203 * of a 64-bit unsigned integer. The first ID
204 * generated is 1 and the value will be
205 * incremented for each thread ID.
207 * C* metadata keys starting with C indicate
208 * configuration data. It can be managed with the
209 * n_database_*config* API. There is a convention
210 * of hierarchical keys separated by '.' (e.g.
211 * query.notmuch stores the value for the named
212 * query 'notmuch'), but it is not enforced by the
218 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
219 * Instead, the database has the following additional database
222 * thread_id_* A pre-allocated thread ID for a particular
223 * message. This is actually an arbitrarily large
224 * family of metadata name. Any particular name is
225 * formed by concatenating "thread_id_" with a message
226 * ID (or the SHA1 sum of a message ID if it is very
227 * long---see description of 'id' in the mail
228 * document). The value stored is a thread ID.
230 * These thread ID metadata values are stored
231 * whenever a message references a parent message
232 * that does not yet exist in the database. A
233 * thread ID will be allocated and stored, and if
234 * the message is later added, the stored thread
235 * ID will be used (and the metadata value will
238 * Even before a message is added, it's
239 * pre-allocated thread ID is useful so that all
240 * descendant messages that reference this common
241 * parent can be recognized as belonging to the
245 /* With these prefix values we follow the conventions published here:
247 * https://xapian.org/docs/omega/termprefixes.html
249 * as much as makes sense. Note that I took some liberty in matching
250 * the reserved prefix values to notmuch concepts, (for example, 'G'
251 * is documented as "newsGroup (or similar entity - e.g. a web forum
252 * name)", for which I think the thread is the closest analogue in
253 * notmuch. This in spite of the fact that we will eventually be
254 * storing mailing-list messages where 'G' for "mailing list name"
255 * might be even a closer analogue. I'm treating the single-character
256 * prefixes preferentially for core notmuch concepts (which will be
257 * nearly universal to all mail messages).
261 prefix_t prefix_table[] = {
262 /* name term prefix flags */
263 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
264 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
265 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
266 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
267 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
268 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
269 { "thread", "G", NOTMUCH_FIELD_EXTERNAL |
270 NOTMUCH_FIELD_PROCESSOR },
271 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
272 NOTMUCH_FIELD_PROCESSOR },
273 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
274 NOTMUCH_FIELD_PROCESSOR },
275 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
276 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
277 NOTMUCH_FIELD_PROCESSOR },
278 { "path", "P", NOTMUCH_FIELD_EXTERNAL|
279 NOTMUCH_FIELD_PROCESSOR },
280 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
282 * Unconditionally add ':' to reduce potential ambiguity with
283 * overlapping prefixes and/or terms that start with capital
284 * letters. See Xapian document termprefixes.html for related
287 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
288 NOTMUCH_FIELD_PROCESSOR },
289 #if HAVE_XAPIAN_FIELD_PROCESSOR
290 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
291 NOTMUCH_FIELD_PROCESSOR },
292 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
293 NOTMUCH_FIELD_PROCESSOR },
295 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
296 NOTMUCH_FIELD_PROBABILISTIC |
297 NOTMUCH_FIELD_PROCESSOR },
298 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
299 NOTMUCH_FIELD_PROBABILISTIC },
300 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
301 NOTMUCH_FIELD_PROBABILISTIC },
302 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
303 NOTMUCH_FIELD_PROBABILISTIC },
304 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
305 NOTMUCH_FIELD_PROBABILISTIC |
306 NOTMUCH_FIELD_PROCESSOR},
310 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
312 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
313 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
315 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
318 #if HAVE_XAPIAN_FIELD_PROCESSOR
320 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
322 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
323 Xapian::FieldProcessor *fp;
325 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
326 fp = (new DateFieldProcessor())->release ();
327 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
328 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
329 else if (STRNCMP_LITERAL(prefix->name, "thread") == 0)
330 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
332 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
333 *notmuch->query_parser, notmuch))->release ();
335 /* we treat all field-processor fields as boolean in order to get the raw input */
336 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
338 _setup_query_field_default (prefix, notmuch);
343 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
345 _setup_query_field_default (prefix, notmuch);
350 _find_prefix (const char *name)
354 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
355 if (strcmp (name, prefix_table[i].name) == 0)
356 return prefix_table[i].prefix;
359 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
364 static const struct {
365 /* NOTMUCH_FEATURE_* value. */
366 _notmuch_features value;
367 /* Feature name as it appears in the database. This name should
368 * be appropriate for displaying to the user if an older version
369 * of notmuch doesn't support this feature. */
371 /* Compatibility flags when this feature is declared. */
373 } feature_names[] = {
374 { NOTMUCH_FEATURE_FILE_TERMS,
375 "multiple paths per message", "rw" },
376 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
377 "relative directory paths", "rw" },
378 /* Header values are not required for reading a database because a
379 * reader can just refer to the message file. */
380 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
381 "from/subject/message-ID in database", "w" },
382 { NOTMUCH_FEATURE_BOOL_FOLDER,
383 "exact folder:/path: search", "rw" },
384 { NOTMUCH_FEATURE_GHOSTS,
385 "mail documents for missing messages", "w"},
386 /* Knowledge of the index mime-types are not required for reading
387 * a database because a reader will just be unable to query
389 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
390 "indexed MIME types", "w"},
391 { NOTMUCH_FEATURE_LAST_MOD,
392 "modification tracking", "w"},
396 notmuch_status_to_string (notmuch_status_t status)
399 case NOTMUCH_STATUS_SUCCESS:
400 return "No error occurred";
401 case NOTMUCH_STATUS_OUT_OF_MEMORY:
402 return "Out of memory";
403 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
404 return "Attempt to write to a read-only database";
405 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
406 return "A Xapian exception occurred";
407 case NOTMUCH_STATUS_FILE_ERROR:
408 return "Something went wrong trying to read or write a file";
409 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
410 return "File is not an email";
411 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
412 return "Message ID is identical to a message in database";
413 case NOTMUCH_STATUS_NULL_POINTER:
414 return "Erroneous NULL pointer";
415 case NOTMUCH_STATUS_TAG_TOO_LONG:
416 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
417 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
418 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
419 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
420 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
421 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
422 return "Unsupported operation";
423 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
424 return "Operation requires a database upgrade";
425 case NOTMUCH_STATUS_PATH_ERROR:
426 return "Path supplied is illegal for this function";
427 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
428 return "Crypto protocol missing, malformed, or unintelligible";
429 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
430 return "Crypto engine initialization failure";
431 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
432 return "Unknown crypto protocol";
434 case NOTMUCH_STATUS_LAST_STATUS:
435 return "Unknown error status value";
440 _notmuch_database_log (notmuch_database_t *notmuch,
446 va_start (va_args, format);
448 if (notmuch->status_string)
449 talloc_free (notmuch->status_string);
451 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
456 _notmuch_database_log_append (notmuch_database_t *notmuch,
462 va_start (va_args, format);
464 if (notmuch->status_string)
465 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
467 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
473 find_doc_ids_for_term (notmuch_database_t *notmuch,
475 Xapian::PostingIterator *begin,
476 Xapian::PostingIterator *end)
478 *begin = notmuch->xapian_db->postlist_begin (term);
480 *end = notmuch->xapian_db->postlist_end (term);
484 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
485 const char *prefix_name,
487 Xapian::PostingIterator *begin,
488 Xapian::PostingIterator *end)
492 term = talloc_asprintf (notmuch, "%s%s",
493 _find_prefix (prefix_name), value);
495 find_doc_ids_for_term (notmuch, term, begin, end);
500 notmuch_private_status_t
501 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
502 const char *prefix_name,
504 unsigned int *doc_id)
506 Xapian::PostingIterator i, end;
508 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
512 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
517 #if DEBUG_DATABASE_SANITY
521 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
525 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
528 static Xapian::Document
529 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
531 return notmuch->xapian_db->get_document (doc_id);
534 /* Generate a compressed version of 'message_id' of the form:
536 * notmuch-sha1-<sha1_sum_of_message_id>
539 _notmuch_message_id_compressed (void *ctx, const char *message_id)
541 char *sha1, *compressed;
543 sha1 = _notmuch_sha1_of_string (message_id);
545 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
552 notmuch_database_find_message (notmuch_database_t *notmuch,
553 const char *message_id,
554 notmuch_message_t **message_ret)
556 notmuch_private_status_t status;
559 if (message_ret == NULL)
560 return NOTMUCH_STATUS_NULL_POINTER;
562 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
563 message_id = _notmuch_message_id_compressed (notmuch, message_id);
566 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
567 message_id, &doc_id);
569 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
572 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
574 if (*message_ret == NULL)
575 return NOTMUCH_STATUS_OUT_OF_MEMORY;
578 return NOTMUCH_STATUS_SUCCESS;
579 } catch (const Xapian::Error &error) {
580 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
581 error.get_msg().c_str());
582 notmuch->exception_reported = true;
584 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
589 notmuch_database_create (const char *path, notmuch_database_t **database)
591 char *status_string = NULL;
592 notmuch_status_t status;
594 status = notmuch_database_create_verbose (path, database,
598 fputs (status_string, stderr);
599 free (status_string);
606 notmuch_database_create_verbose (const char *path,
607 notmuch_database_t **database,
608 char **status_string)
610 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
611 notmuch_database_t *notmuch = NULL;
612 char *notmuch_path = NULL;
613 char *message = NULL;
618 message = strdup ("Error: Cannot create a database for a NULL path.\n");
619 status = NOTMUCH_STATUS_NULL_POINTER;
623 if (path[0] != '/') {
624 message = strdup ("Error: Database path must be absolute.\n");
625 status = NOTMUCH_STATUS_PATH_ERROR;
629 err = stat (path, &st);
631 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
632 path, strerror (errno)));
633 status = NOTMUCH_STATUS_FILE_ERROR;
637 if (! S_ISDIR (st.st_mode)) {
638 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
639 "Not a directory.\n",
641 status = NOTMUCH_STATUS_FILE_ERROR;
645 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
647 err = mkdir (notmuch_path, 0755);
650 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
651 notmuch_path, strerror (errno)));
652 status = NOTMUCH_STATUS_FILE_ERROR;
656 status = notmuch_database_open_verbose (path,
657 NOTMUCH_DATABASE_MODE_READ_WRITE,
662 /* Upgrade doesn't add these feature to existing databases, but
663 * new databases have them. */
664 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
665 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
667 status = notmuch_database_upgrade (notmuch, NULL, NULL);
669 notmuch_database_close(notmuch);
675 talloc_free (notmuch_path);
679 *status_string = message;
686 talloc_free (notmuch);
691 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
693 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
694 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
695 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
698 return NOTMUCH_STATUS_SUCCESS;
701 /* Allocate a revision number for the next change. */
703 _notmuch_database_new_revision (notmuch_database_t *notmuch)
705 unsigned long new_revision = notmuch->revision + 1;
707 /* If we're in an atomic section, hold off on updating the
708 * committed revision number until we commit the atomic section.
710 if (notmuch->atomic_nesting)
711 notmuch->atomic_dirty = true;
713 notmuch->revision = new_revision;
718 /* Parse a database features string from the given database version.
719 * Returns the feature bit set.
721 * For version < 3, this ignores the features string and returns a
722 * hard-coded set of features.
724 * If there are unrecognized features that are required to open the
725 * database in mode (which should be 'r' or 'w'), return a
726 * comma-separated list of unrecognized but required features in
727 * *incompat_out suitable for presenting to the user. *incompat_out
728 * will be allocated from ctx.
730 static _notmuch_features
731 _parse_features (const void *ctx, const char *features, unsigned int version,
732 char mode, char **incompat_out)
734 _notmuch_features res = static_cast<_notmuch_features>(0);
735 unsigned int namelen, i;
739 /* Prior to database version 3, features were implied by the
742 return NOTMUCH_FEATURES_V0;
743 else if (version == 1)
744 return NOTMUCH_FEATURES_V1;
745 else if (version == 2)
746 return NOTMUCH_FEATURES_V2;
748 /* Parse the features string */
749 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
750 flags = strchr (features, '\t');
751 if (! flags || flags > features + llen)
753 namelen = flags - features;
755 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
756 if (strlen (feature_names[i].name) == namelen &&
757 strncmp (feature_names[i].name, features, namelen) == 0) {
758 res |= feature_names[i].value;
763 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
764 /* Unrecognized feature */
765 const char *have = strchr (flags, mode);
766 if (have && have < features + llen) {
767 /* This feature is required to access this database in
768 * 'mode', but we don't understand it. */
770 *incompat_out = talloc_strdup (ctx, "");
771 *incompat_out = talloc_asprintf_append_buffer (
772 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
782 _print_features (const void *ctx, unsigned int features)
785 char *res = talloc_strdup (ctx, "");
787 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
788 if (features & feature_names[i].value)
789 res = talloc_asprintf_append_buffer (
790 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
796 notmuch_database_open (const char *path,
797 notmuch_database_mode_t mode,
798 notmuch_database_t **database)
800 char *status_string = NULL;
801 notmuch_status_t status;
803 status = notmuch_database_open_verbose (path, mode, database,
807 fputs (status_string, stderr);
808 free (status_string);
815 notmuch_database_open_verbose (const char *path,
816 notmuch_database_mode_t mode,
817 notmuch_database_t **database,
818 char **status_string)
820 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
821 void *local = talloc_new (NULL);
822 notmuch_database_t *notmuch = NULL;
823 char *notmuch_path, *xapian_path, *incompat_features;
824 char *message = NULL;
827 unsigned int i, version;
828 static int initialized = 0;
831 message = strdup ("Error: Cannot open a database for a NULL path.\n");
832 status = NOTMUCH_STATUS_NULL_POINTER;
836 if (path[0] != '/') {
837 message = strdup ("Error: Database path must be absolute.\n");
838 status = NOTMUCH_STATUS_PATH_ERROR;
842 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
843 message = strdup ("Out of memory\n");
844 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
848 err = stat (notmuch_path, &st);
850 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
851 notmuch_path, strerror (errno)));
852 status = NOTMUCH_STATUS_FILE_ERROR;
856 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
857 message = strdup ("Out of memory\n");
858 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
862 /* Initialize the GLib type system and threads */
863 #if !GLIB_CHECK_VERSION(2, 35, 1)
867 /* Initialize gmime */
869 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
873 notmuch = talloc_zero (NULL, notmuch_database_t);
874 notmuch->exception_reported = false;
875 notmuch->status_string = NULL;
876 notmuch->path = talloc_strdup (notmuch, path);
878 strip_trailing(notmuch->path, '/');
880 notmuch->mode = mode;
881 notmuch->atomic_nesting = 0;
884 string last_thread_id;
887 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
888 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
891 notmuch->xapian_db = new Xapian::Database (xapian_path);
894 /* Check version. As of database version 3, we represent
895 * changes in terms of features, so assume a version bump
896 * means a dramatically incompatible change. */
897 version = notmuch_database_get_version (notmuch);
898 if (version > NOTMUCH_DATABASE_VERSION) {
899 IGNORE_RESULT (asprintf (&message,
900 "Error: Notmuch database at %s\n"
901 " has a newer database format version (%u) than supported by this\n"
902 " version of notmuch (%u).\n",
903 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
904 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
905 notmuch_database_destroy (notmuch);
907 status = NOTMUCH_STATUS_FILE_ERROR;
911 /* Check features. */
912 incompat_features = NULL;
913 notmuch->features = _parse_features (
914 local, notmuch->xapian_db->get_metadata ("features").c_str (),
915 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
917 if (incompat_features) {
918 IGNORE_RESULT (asprintf (&message,
919 "Error: Notmuch database at %s\n"
920 " requires features (%s)\n"
921 " not supported by this version of notmuch.\n",
922 notmuch_path, incompat_features));
923 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
924 notmuch_database_destroy (notmuch);
926 status = NOTMUCH_STATUS_FILE_ERROR;
930 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
931 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
932 if (last_thread_id.empty ()) {
933 notmuch->last_thread_id = 0;
938 str = last_thread_id.c_str ();
939 notmuch->last_thread_id = strtoull (str, &end, 16);
941 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
944 /* Get current highest revision number. */
945 last_mod = notmuch->xapian_db->get_value_upper_bound (
946 NOTMUCH_VALUE_LAST_MOD);
947 if (last_mod.empty ())
948 notmuch->revision = 0;
950 notmuch->revision = Xapian::sortable_unserialise (last_mod);
951 notmuch->uuid = talloc_strdup (
952 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
954 notmuch->query_parser = new Xapian::QueryParser;
955 notmuch->term_gen = new Xapian::TermGenerator;
956 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
957 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
958 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
959 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
961 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
962 notmuch->query_parser->set_database (*notmuch->xapian_db);
963 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
964 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
965 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
966 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
967 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
969 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
970 const prefix_t *prefix = &prefix_table[i];
971 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
972 _setup_query_field (prefix, notmuch);
975 } catch (const Xapian::Error &error) {
976 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
977 error.get_msg().c_str()));
978 notmuch_database_destroy (notmuch);
980 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
988 *status_string = message;
996 talloc_free (notmuch);
1001 notmuch_database_close (notmuch_database_t *notmuch)
1003 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1005 /* Many Xapian objects (and thus notmuch objects) hold references to
1006 * the database, so merely deleting the database may not suffice to
1007 * close it. Thus, we explicitly close it here. */
1008 if (notmuch->xapian_db != NULL) {
1010 /* If there's an outstanding transaction, it's unclear if
1011 * closing the Xapian database commits everything up to
1012 * that transaction, or may discard committed (but
1013 * unflushed) transactions. To be certain, explicitly
1014 * cancel any outstanding transaction before closing. */
1015 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1016 notmuch->atomic_nesting)
1017 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1018 ->cancel_transaction ();
1020 /* Close the database. This implicitly flushes
1021 * outstanding changes. */
1022 notmuch->xapian_db->close();
1023 } catch (const Xapian::Error &error) {
1024 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1025 if (! notmuch->exception_reported) {
1026 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1027 error.get_msg().c_str());
1032 delete notmuch->term_gen;
1033 notmuch->term_gen = NULL;
1034 delete notmuch->query_parser;
1035 notmuch->query_parser = NULL;
1036 delete notmuch->xapian_db;
1037 notmuch->xapian_db = NULL;
1038 delete notmuch->value_range_processor;
1039 notmuch->value_range_processor = NULL;
1040 delete notmuch->date_range_processor;
1041 notmuch->date_range_processor = NULL;
1042 delete notmuch->last_mod_range_processor;
1043 notmuch->last_mod_range_processor = NULL;
1049 _notmuch_database_reopen (notmuch_database_t *notmuch)
1051 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1052 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1055 notmuch->xapian_db->reopen ();
1056 } catch (const Xapian::Error &error) {
1057 if (! notmuch->exception_reported) {
1058 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1059 error.get_msg ().c_str ());
1060 notmuch->exception_reported = true;
1062 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1067 return NOTMUCH_STATUS_SUCCESS;
1071 unlink_cb (const char *path,
1072 unused (const struct stat *sb),
1074 unused (struct FTW *ftw))
1076 return remove (path);
1080 rmtree (const char *path)
1082 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1085 class NotmuchCompactor : public Xapian::Compactor
1087 notmuch_compact_status_cb_t status_cb;
1088 void *status_closure;
1091 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1092 status_cb (cb), status_closure (closure) { }
1095 set_status (const std::string &table, const std::string &status)
1099 if (status_cb == NULL)
1102 if (status.length () == 0)
1103 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1105 msg = talloc_asprintf (NULL, " %s", status.c_str());
1111 status_cb (msg, status_closure);
1116 /* Compacts the given database, optionally saving the original database
1117 * in backup_path. Additionally, a callback function can be provided to
1118 * give the user feedback on the progress of the (likely long-lived)
1119 * compaction process.
1121 * The backup path must point to a directory on the same volume as the
1122 * original database. Passing a NULL backup_path will result in the
1123 * uncompacted database being deleted after compaction has finished.
1124 * Note that the database write lock will be held during the
1125 * compaction process to protect data integrity.
1128 notmuch_database_compact (const char *path,
1129 const char *backup_path,
1130 notmuch_compact_status_cb_t status_cb,
1134 char *notmuch_path, *xapian_path, *compact_xapian_path;
1135 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1136 notmuch_database_t *notmuch = NULL;
1137 struct stat statbuf;
1139 char *message = NULL;
1141 local = talloc_new (NULL);
1143 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1145 ret = notmuch_database_open_verbose (path,
1146 NOTMUCH_DATABASE_MODE_READ_WRITE,
1150 if (status_cb) status_cb (message, closure);
1154 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1155 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1159 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1160 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1164 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1165 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1169 if (backup_path == NULL) {
1170 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1171 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1174 keep_backup = false;
1180 if (stat (backup_path, &statbuf) != -1) {
1181 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1182 ret = NOTMUCH_STATUS_FILE_ERROR;
1185 if (errno != ENOENT) {
1186 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1188 ret = NOTMUCH_STATUS_FILE_ERROR;
1192 /* Unconditionally attempt to remove old work-in-progress database (if
1193 * any). This is "protected" by database lock. If this fails due to write
1194 * errors (etc), the following code will fail and provide error message.
1196 (void) rmtree (compact_xapian_path);
1199 NotmuchCompactor compactor (status_cb, closure);
1201 compactor.set_renumber (false);
1202 compactor.add_source (xapian_path);
1203 compactor.set_destdir (compact_xapian_path);
1204 compactor.compact ();
1205 } catch (const Xapian::Error &error) {
1206 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1207 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1211 if (rename (xapian_path, backup_path)) {
1212 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1213 xapian_path, backup_path, strerror (errno));
1214 ret = NOTMUCH_STATUS_FILE_ERROR;
1218 if (rename (compact_xapian_path, xapian_path)) {
1219 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1220 compact_xapian_path, xapian_path, strerror (errno));
1221 ret = NOTMUCH_STATUS_FILE_ERROR;
1225 if (! keep_backup) {
1226 if (rmtree (backup_path)) {
1227 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1228 backup_path, strerror (errno));
1229 ret = NOTMUCH_STATUS_FILE_ERROR;
1236 notmuch_status_t ret2;
1238 const char *str = notmuch_database_status_string (notmuch);
1239 if (status_cb && str)
1240 status_cb (str, closure);
1242 ret2 = notmuch_database_destroy (notmuch);
1244 /* don't clobber previous error status */
1245 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1249 talloc_free (local);
1255 notmuch_database_destroy (notmuch_database_t *notmuch)
1257 notmuch_status_t status;
1259 status = notmuch_database_close (notmuch);
1260 talloc_free (notmuch);
1266 notmuch_database_get_path (notmuch_database_t *notmuch)
1268 return notmuch->path;
1272 notmuch_database_get_version (notmuch_database_t *notmuch)
1274 unsigned int version;
1275 string version_string;
1279 version_string = notmuch->xapian_db->get_metadata ("version");
1280 if (version_string.empty ())
1283 str = version_string.c_str ();
1284 if (str == NULL || *str == '\0')
1287 version = strtoul (str, &end, 10);
1289 INTERNAL_ERROR ("Malformed database version: %s", str);
1295 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1297 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1298 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1299 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1302 static volatile sig_atomic_t do_progress_notify = 0;
1305 handle_sigalrm (unused (int signal))
1307 do_progress_notify = 1;
1310 /* Upgrade the current database.
1312 * After opening a database in read-write mode, the client should
1313 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1314 * if so, upgrade with this function before making any modifications.
1316 * The optional progress_notify callback can be used by the caller to
1317 * provide progress indication to the user. If non-NULL it will be
1318 * called periodically with 'count' as the number of messages upgraded
1319 * so far and 'total' the overall number of messages that will be
1323 notmuch_database_upgrade (notmuch_database_t *notmuch,
1324 void (*progress_notify) (void *closure,
1328 void *local = talloc_new (NULL);
1329 Xapian::TermIterator t, t_end;
1330 Xapian::WritableDatabase *db;
1331 struct sigaction action;
1332 struct itimerval timerval;
1333 bool timer_is_active = false;
1334 enum _notmuch_features target_features, new_features;
1335 notmuch_status_t status;
1336 notmuch_private_status_t private_status;
1337 notmuch_query_t *query = NULL;
1338 unsigned int count = 0, total = 0;
1340 status = _notmuch_database_ensure_writable (notmuch);
1344 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1346 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1347 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1349 if (! notmuch_database_needs_upgrade (notmuch))
1350 return NOTMUCH_STATUS_SUCCESS;
1352 if (progress_notify) {
1353 /* Set up our handler for SIGALRM */
1354 memset (&action, 0, sizeof (struct sigaction));
1355 action.sa_handler = handle_sigalrm;
1356 sigemptyset (&action.sa_mask);
1357 action.sa_flags = SA_RESTART;
1358 sigaction (SIGALRM, &action, NULL);
1360 /* Then start a timer to send SIGALRM once per second. */
1361 timerval.it_interval.tv_sec = 1;
1362 timerval.it_interval.tv_usec = 0;
1363 timerval.it_value.tv_sec = 1;
1364 timerval.it_value.tv_usec = 0;
1365 setitimer (ITIMER_REAL, &timerval, NULL);
1367 timer_is_active = true;
1370 /* Figure out how much total work we need to do. */
1372 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1373 NOTMUCH_FEATURE_LAST_MOD)) {
1374 query = notmuch_query_create (notmuch, "");
1377 status = notmuch_query_count_messages (query, &msg_count);
1382 notmuch_query_destroy (query);
1385 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1386 t_end = db->allterms_end ("XTIMESTAMP");
1387 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1390 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1391 /* The ghost message upgrade converts all thread_id_*
1392 * metadata values into ghost message documents. */
1393 t_end = db->metadata_keys_end ("thread_id_");
1394 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1398 /* Perform the upgrade in a transaction. */
1399 db->begin_transaction (true);
1401 /* Set the target features so we write out changes in the desired
1403 notmuch->features = target_features;
1405 /* Perform per-message upgrades. */
1407 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1408 NOTMUCH_FEATURE_LAST_MOD)) {
1409 notmuch_messages_t *messages;
1410 notmuch_message_t *message;
1413 query = notmuch_query_create (notmuch, "");
1415 status = notmuch_query_search_messages (query, &messages);
1419 notmuch_messages_valid (messages);
1420 notmuch_messages_move_to_next (messages))
1422 if (do_progress_notify) {
1423 progress_notify (closure, (double) count / total);
1424 do_progress_notify = 0;
1427 message = notmuch_messages_get (messages);
1429 /* Before version 1, each message document had its
1430 * filename in the data field. Copy that into the new
1431 * format by calling notmuch_message_add_filename.
1433 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1434 filename = _notmuch_message_talloc_copy_data (message);
1435 if (filename && *filename != '\0') {
1436 _notmuch_message_add_filename (message, filename);
1437 _notmuch_message_clear_data (message);
1439 talloc_free (filename);
1442 /* Prior to version 2, the "folder:" prefix was
1443 * probabilistic and stemmed. Change it to the current
1444 * boolean prefix. Add "path:" prefixes while at it.
1446 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1447 _notmuch_message_upgrade_folder (message);
1449 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1450 * track modification revisions. Give all messages the
1451 * next available revision; since we just started tracking
1452 * revisions for this database, that will be 1.
1454 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1455 _notmuch_message_upgrade_last_mod (message);
1457 _notmuch_message_sync (message);
1459 notmuch_message_destroy (message);
1464 notmuch_query_destroy (query);
1468 /* Perform per-directory upgrades. */
1470 /* Before version 1 we stored directory timestamps in
1471 * XTIMESTAMP documents instead of the current XDIRECTORY
1472 * documents. So copy those as well. */
1473 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1474 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1476 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1480 Xapian::PostingIterator p, p_end;
1481 std::string term = *t;
1483 p_end = notmuch->xapian_db->postlist_end (term);
1485 for (p = notmuch->xapian_db->postlist_begin (term);
1489 Xapian::Document document;
1491 notmuch_directory_t *directory;
1493 if (do_progress_notify) {
1494 progress_notify (closure, (double) count / total);
1495 do_progress_notify = 0;
1498 document = find_document_for_doc_id (notmuch, *p);
1499 mtime = Xapian::sortable_unserialise (
1500 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1502 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1503 NOTMUCH_FIND_CREATE, &status);
1504 notmuch_directory_set_mtime (directory, mtime);
1505 notmuch_directory_destroy (directory);
1507 db->delete_document (*p);
1514 /* Perform metadata upgrades. */
1516 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1517 * messages were stored as database metadata. Change these to
1520 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1521 notmuch_message_t *message;
1522 std::string message_id, thread_id;
1524 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1525 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1527 if (do_progress_notify) {
1528 progress_notify (closure, (double) count / total);
1529 do_progress_notify = 0;
1532 message_id = (*t).substr (
1533 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1534 thread_id = db->get_metadata (*t);
1536 /* Create ghost message */
1537 message = _notmuch_message_create_for_message_id (
1538 notmuch, message_id.c_str (), &private_status);
1539 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1540 /* Document already exists; ignore the stored thread ID */
1541 } else if (private_status ==
1542 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1543 private_status = _notmuch_message_initialize_ghost (
1544 message, thread_id.c_str ());
1545 if (! private_status)
1546 _notmuch_message_sync (message);
1549 if (private_status) {
1550 _notmuch_database_log (notmuch,
1551 "Upgrade failed while creating ghost messages.\n");
1552 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1556 /* Clear saved metadata thread ID */
1557 db->set_metadata (*t, "");
1563 status = NOTMUCH_STATUS_SUCCESS;
1564 db->set_metadata ("features", _print_features (local, notmuch->features));
1565 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1568 if (status == NOTMUCH_STATUS_SUCCESS)
1569 db->commit_transaction ();
1571 db->cancel_transaction ();
1573 if (timer_is_active) {
1574 /* Now stop the timer. */
1575 timerval.it_interval.tv_sec = 0;
1576 timerval.it_interval.tv_usec = 0;
1577 timerval.it_value.tv_sec = 0;
1578 timerval.it_value.tv_usec = 0;
1579 setitimer (ITIMER_REAL, &timerval, NULL);
1581 /* And disable the signal handler. */
1582 action.sa_handler = SIG_IGN;
1583 sigaction (SIGALRM, &action, NULL);
1587 notmuch_query_destroy (query);
1589 talloc_free (local);
1594 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1596 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1597 notmuch->atomic_nesting > 0)
1600 if (notmuch_database_needs_upgrade (notmuch))
1601 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1604 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1605 } catch (const Xapian::Error &error) {
1606 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1607 error.get_msg().c_str());
1608 notmuch->exception_reported = true;
1609 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1613 notmuch->atomic_nesting++;
1614 return NOTMUCH_STATUS_SUCCESS;
1618 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1620 Xapian::WritableDatabase *db;
1622 if (notmuch->atomic_nesting == 0)
1623 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1625 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1626 notmuch->atomic_nesting > 1)
1629 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1631 db->commit_transaction ();
1633 /* This is a hack for testing. Xapian never flushes on a
1634 * non-flushed commit, even if the flush threshold is 1.
1635 * However, we rely on flushing to test atomicity. */
1636 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1637 if (thresh && atoi (thresh) == 1)
1639 } catch (const Xapian::Error &error) {
1640 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1641 error.get_msg().c_str());
1642 notmuch->exception_reported = true;
1643 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1646 if (notmuch->atomic_dirty) {
1647 ++notmuch->revision;
1648 notmuch->atomic_dirty = false;
1652 notmuch->atomic_nesting--;
1653 return NOTMUCH_STATUS_SUCCESS;
1657 notmuch_database_get_revision (notmuch_database_t *notmuch,
1661 *uuid = notmuch->uuid;
1662 return notmuch->revision;
1665 /* We allow the user to use arbitrarily long paths for directories. But
1666 * we have a term-length limit. So if we exceed that, we'll use the
1667 * SHA-1 of the path for the database term.
1669 * Note: This function may return the original value of 'path'. If it
1670 * does not, then the caller is responsible to free() the returned
1674 _notmuch_database_get_directory_db_path (const char *path)
1676 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1678 if (term_len > NOTMUCH_TERM_MAX)
1679 return _notmuch_sha1_of_string (path);
1684 /* Given a path, split it into two parts: the directory part is all
1685 * components except for the last, and the basename is that last
1686 * component. Getting the return-value for either part is optional
1687 * (the caller can pass NULL).
1689 * The original 'path' can represent either a regular file or a
1690 * directory---the splitting will be carried out in the same way in
1691 * either case. Trailing slashes on 'path' will be ignored, and any
1692 * cases of multiple '/' characters appearing in series will be
1693 * treated as a single '/'.
1695 * Allocation (if any) will have 'ctx' as the talloc owner. But
1696 * pointers will be returned within the original path string whenever
1699 * Note: If 'path' is non-empty and contains no non-trailing slash,
1700 * (that is, consists of a filename with no parent directory), then
1701 * the directory returned will be an empty string. However, if 'path'
1702 * is an empty string, then both directory and basename will be
1706 _notmuch_database_split_path (void *ctx,
1708 const char **directory,
1709 const char **basename)
1713 if (path == NULL || *path == '\0') {
1718 return NOTMUCH_STATUS_SUCCESS;
1721 /* Find the last slash (not counting a trailing slash), if any. */
1723 slash = path + strlen (path) - 1;
1725 /* First, skip trailing slashes. */
1726 while (slash != path && *slash == '/')
1729 /* Then, find a slash. */
1730 while (slash != path && *slash != '/') {
1737 /* Finally, skip multiple slashes. */
1738 while (slash != path && *(slash - 1) == '/')
1741 if (slash == path) {
1743 *directory = talloc_strdup (ctx, "");
1748 *directory = talloc_strndup (ctx, path, slash - path);
1751 return NOTMUCH_STATUS_SUCCESS;
1754 /* Find the document ID of the specified directory.
1756 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1757 * created if one does not exist for 'path'. Otherwise, if the
1758 * directory document does not exist, this sets *directory_id to
1759 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1762 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1764 notmuch_find_flags_t flags,
1765 unsigned int *directory_id)
1767 notmuch_directory_t *directory;
1768 notmuch_status_t status;
1772 return NOTMUCH_STATUS_SUCCESS;
1775 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1776 if (status || !directory) {
1781 *directory_id = _notmuch_directory_get_document_id (directory);
1783 notmuch_directory_destroy (directory);
1785 return NOTMUCH_STATUS_SUCCESS;
1789 _notmuch_database_get_directory_path (void *ctx,
1790 notmuch_database_t *notmuch,
1791 unsigned int doc_id)
1793 Xapian::Document document;
1795 document = find_document_for_doc_id (notmuch, doc_id);
1797 return talloc_strdup (ctx, document.get_data ().c_str ());
1800 /* Given a legal 'filename' for the database, (either relative to
1801 * database path or absolute with initial components identical to
1802 * database path), return a new string (with 'ctx' as the talloc
1803 * owner) suitable for use as a direntry term value.
1805 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1806 * will be created in the database as needed. Otherwise, if the
1807 * necessary directory documents do not exist, this sets
1808 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1811 _notmuch_database_filename_to_direntry (void *ctx,
1812 notmuch_database_t *notmuch,
1813 const char *filename,
1814 notmuch_find_flags_t flags,
1817 const char *relative, *directory, *basename;
1818 Xapian::docid directory_id;
1819 notmuch_status_t status;
1821 relative = _notmuch_database_relative_path (notmuch, filename);
1823 status = _notmuch_database_split_path (ctx, relative,
1824 &directory, &basename);
1828 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1830 if (status || directory_id == (unsigned int)-1) {
1835 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1837 return NOTMUCH_STATUS_SUCCESS;
1840 /* Given a legal 'path' for the database, return the relative path.
1842 * The return value will be a pointer to the original path contents,
1843 * and will be either the original string (if 'path' was relative) or
1844 * a portion of the string (if path was absolute and begins with the
1848 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1851 const char *db_path, *relative;
1852 unsigned int db_path_len;
1854 db_path = notmuch_database_get_path (notmuch);
1855 db_path_len = strlen (db_path);
1859 if (*relative == '/') {
1860 while (*relative == '/' && *(relative+1) == '/')
1863 if (strncmp (relative, db_path, db_path_len) == 0)
1865 relative += db_path_len;
1866 while (*relative == '/')
1875 notmuch_database_get_directory (notmuch_database_t *notmuch,
1877 notmuch_directory_t **directory)
1879 notmuch_status_t status;
1881 if (directory == NULL)
1882 return NOTMUCH_STATUS_NULL_POINTER;
1886 *directory = _notmuch_directory_create (notmuch, path,
1887 NOTMUCH_FIND_LOOKUP, &status);
1888 } catch (const Xapian::Error &error) {
1889 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1890 error.get_msg().c_str());
1891 notmuch->exception_reported = true;
1892 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1897 /* Allocate a document ID that satisfies the following criteria:
1899 * 1. The ID does not exist for any document in the Xapian database
1901 * 2. The ID was not previously returned from this function
1903 * 3. The ID is the smallest integer satisfying (1) and (2)
1905 * This function will trigger an internal error if these constraints
1906 * cannot all be satisfied, (that is, the pool of available document
1907 * IDs has been exhausted).
1910 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1912 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1914 notmuch->last_doc_id++;
1916 if (notmuch->last_doc_id == 0)
1917 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1919 return notmuch->last_doc_id;
1923 notmuch_database_remove_message (notmuch_database_t *notmuch,
1924 const char *filename)
1926 notmuch_status_t status;
1927 notmuch_message_t *message;
1929 status = notmuch_database_find_message_by_filename (notmuch, filename,
1932 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1933 status = _notmuch_message_remove_filename (message, filename);
1934 if (status == NOTMUCH_STATUS_SUCCESS)
1935 _notmuch_message_delete (message);
1936 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1937 _notmuch_message_sync (message);
1939 notmuch_message_destroy (message);
1946 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1947 const char *filename,
1948 notmuch_message_t **message_ret)
1951 const char *prefix = _find_prefix ("file-direntry");
1952 char *direntry, *term;
1953 Xapian::PostingIterator i, end;
1954 notmuch_status_t status;
1956 if (message_ret == NULL)
1957 return NOTMUCH_STATUS_NULL_POINTER;
1959 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1960 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1962 /* return NULL on any failure */
1963 *message_ret = NULL;
1965 local = talloc_new (notmuch);
1968 status = _notmuch_database_filename_to_direntry (
1969 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1970 if (status || !direntry)
1973 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1975 find_doc_ids_for_term (notmuch, term, &i, &end);
1978 notmuch_private_status_t private_status;
1980 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1982 if (*message_ret == NULL)
1983 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1985 } catch (const Xapian::Error &error) {
1986 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1987 error.get_msg().c_str());
1988 notmuch->exception_reported = true;
1989 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1993 talloc_free (local);
1995 if (status && *message_ret) {
1996 notmuch_message_destroy (*message_ret);
1997 *message_ret = NULL;
2002 notmuch_string_list_t *
2003 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2004 Xapian::TermIterator &end,
2007 int prefix_len = strlen (prefix);
2008 notmuch_string_list_t *list;
2010 list = _notmuch_string_list_create (ctx);
2011 if (unlikely (list == NULL))
2014 for (i.skip_to (prefix); i != end; i++) {
2015 /* Terminate loop at first term without desired prefix. */
2016 if (strncmp ((*i).c_str (), prefix, prefix_len))
2019 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2026 notmuch_database_get_all_tags (notmuch_database_t *db)
2028 Xapian::TermIterator i, end;
2029 notmuch_string_list_t *tags;
2032 i = db->xapian_db->allterms_begin();
2033 end = db->xapian_db->allterms_end();
2034 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2035 _find_prefix ("tag"));
2036 _notmuch_string_list_sort (tags);
2037 return _notmuch_tags_create (db, tags);
2038 } catch (const Xapian::Error &error) {
2039 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2040 error.get_msg().c_str());
2041 db->exception_reported = true;
2047 notmuch_database_status_string (const notmuch_database_t *notmuch)
2049 return notmuch->status_string;