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 "regexp-fields.h"
25 #include "string-util.h"
34 #include <glib.h> /* g_free, GPtrArray, GHashTable */
35 #include <glib-object.h> /* g_type_init */
37 #include <gmime/gmime.h> /* g_mime_init */
41 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46 notmuch_field_flag_t flags;
49 #define NOTMUCH_DATABASE_VERSION 3
51 #define STRINGIFY(s) _SUB_STRINGIFY(s)
52 #define _SUB_STRINGIFY(s) #s
54 #if HAVE_XAPIAN_DB_RETRY_LOCK
55 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
57 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
60 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
62 * We currently have three different types of documents (mail, ghost,
63 * and directory) and also some metadata.
67 * A mail document is associated with a particular email message. It
68 * is stored in one or more files on disk (though only one has its
69 * content indexed) and is uniquely identified by its "id" field
70 * (which is generally the message ID). It is indexed with the
71 * following prefixed terms which the database uses to construct
74 * Single terms of given prefix:
78 * id: Unique ID of mail. This is from the Message-ID header
79 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
80 * If it's present and too long, then we use
81 * "notmuch-sha1-<sha1_sum_of_message_id>".
82 * If this header is not present, we use
83 * "notmuch-sha1-<sha1_sum_of_entire_file>".
85 * thread: The ID of the thread to which the mail belongs
87 * replyto: The ID from the In-Reply-To header of the mail (if any).
89 * Multiple terms of given prefix:
91 * reference: All message IDs from In-Reply-To and References
92 * headers in the message.
94 * tag: Any tags associated with this message by the user.
96 * file-direntry: A colon-separated pair of values
97 * (INTEGER:STRING), where INTEGER is the
98 * document ID of a directory document, and
99 * STRING is the name of a file within that
100 * directory for this mail message.
102 * property: Has a property with key=value
103 * FIXME: if no = is present, should match on any value
105 * A mail document also has four values:
107 * TIMESTAMP: The time_t value corresponding to the message's
110 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
112 * FROM: The value of the "From" header
114 * SUBJECT: The value of the "Subject" header
116 * LAST_MOD: The revision number as of the last tag or
119 * In addition, terms from the content of the message are added with
120 * "from", "to", "attachment", and "subject" prefixes for use by the
121 * user in searching. Similarly, terms from the path of the mail
122 * message are added with "folder" and "path" prefixes. But the
123 * database doesn't really care itself about any of these.
125 * The data portion of a mail document is empty.
127 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
128 * -----------------------------------------------
129 * A ghost mail document is like a mail document, but where we don't
130 * have the message content. These are used to track thread reference
131 * information for messages we haven't received.
133 * A ghost mail document has type: ghost; id and thread fields that
134 * are identical to the mail document fields; and a MESSAGE_ID value.
138 * A directory document is used by a client of the notmuch library to
139 * maintain data necessary to allow for efficient polling of mail
142 * All directory documents contain one term:
144 * directory: The directory path (relative to the database path)
145 * Or the SHA1 sum of the directory path (if the
146 * path itself is too long to fit in a Xapian
149 * And all directory documents for directories other than top-level
150 * directories also contain the following term:
152 * directory-direntry: A colon-separated pair of values
153 * (INTEGER:STRING), where INTEGER is the
154 * document ID of the parent directory
155 * document, and STRING is the name of this
156 * directory within that parent.
158 * All directory documents have a single value:
160 * TIMESTAMP: The mtime of the directory (at last scan)
162 * The data portion of a directory document contains the path of the
163 * directory (relative to the database path).
167 * Xapian allows us to store arbitrary name-value pairs as
168 * "metadata". We currently use the following metadata names with the
171 * version The database schema version, (which is distinct
172 * from both the notmuch package version (see
173 * notmuch --version) and the libnotmuch library
174 * version. The version is stored as an base-10
175 * ASCII integer. The initial database version
176 * was 1, (though a schema existed before that
177 * were no "version" database value existed at
178 * all). Successive versions are allocated as
179 * changes are made to the database (such as by
180 * indexing new fields).
182 * features The set of features supported by this
183 * database. This consists of a set of
184 * '\n'-separated lines, where each is a feature
185 * name, a '\t', and compatibility flags. If the
186 * compatibility flags contain 'w', then the
187 * opener must support this feature to safely
188 * write this database. If the compatibility
189 * flags contain 'r', then the opener must
190 * support this feature to read this database.
191 * Introduced in database version 3.
193 * last_thread_id The last thread ID generated. This is stored
194 * as a 16-byte hexadecimal ASCII representation
195 * of a 64-bit unsigned integer. The first ID
196 * generated is 1 and the value will be
197 * incremented for each thread ID.
199 * C* metadata keys starting with C indicate
200 * configuration data. It can be managed with the
201 * n_database_*config* API. There is a convention
202 * of hierarchical keys separated by '.' (e.g.
203 * query.notmuch stores the value for the named
204 * query 'notmuch'), but it is not enforced by the
210 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
211 * Instead, the database has the following additional database
214 * thread_id_* A pre-allocated thread ID for a particular
215 * message. This is actually an arbitrarily large
216 * family of metadata name. Any particular name is
217 * formed by concatenating "thread_id_" with a message
218 * ID (or the SHA1 sum of a message ID if it is very
219 * long---see description of 'id' in the mail
220 * document). The value stored is a thread ID.
222 * These thread ID metadata values are stored
223 * whenever a message references a parent message
224 * that does not yet exist in the database. A
225 * thread ID will be allocated and stored, and if
226 * the message is later added, the stored thread
227 * ID will be used (and the metadata value will
230 * Even before a message is added, it's
231 * pre-allocated thread ID is useful so that all
232 * descendant messages that reference this common
233 * parent can be recognized as belonging to the
237 /* With these prefix values we follow the conventions published here:
239 * https://xapian.org/docs/omega/termprefixes.html
241 * as much as makes sense. Note that I took some liberty in matching
242 * the reserved prefix values to notmuch concepts, (for example, 'G'
243 * is documented as "newsGroup (or similar entity - e.g. a web forum
244 * name)", for which I think the thread is the closest analogue in
245 * notmuch. This in spite of the fact that we will eventually be
246 * storing mailing-list messages where 'G' for "mailing list name"
247 * might be even a closer analogue. I'm treating the single-character
248 * prefixes preferentially for core notmuch concepts (which will be
249 * nearly universal to all mail messages).
253 prefix_t prefix_table[] = {
254 /* name term prefix flags */
255 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
256 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
257 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
258 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
259 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
260 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
261 { "thread", "G", NOTMUCH_FIELD_EXTERNAL },
262 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
263 NOTMUCH_FIELD_PROCESSOR },
264 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
265 NOTMUCH_FIELD_PROCESSOR },
266 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
267 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
268 NOTMUCH_FIELD_PROCESSOR },
269 { "path", "P", NOTMUCH_FIELD_EXTERNAL|
270 NOTMUCH_FIELD_PROCESSOR },
271 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
273 * Unconditionally add ':' to reduce potential ambiguity with
274 * overlapping prefixes and/or terms that start with capital
275 * letters. See Xapian document termprefixes.html for related
278 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
279 NOTMUCH_FIELD_PROCESSOR },
280 #if HAVE_XAPIAN_FIELD_PROCESSOR
281 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
282 NOTMUCH_FIELD_PROCESSOR },
283 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
284 NOTMUCH_FIELD_PROCESSOR },
286 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
287 NOTMUCH_FIELD_PROBABILISTIC |
288 NOTMUCH_FIELD_PROCESSOR },
289 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
290 NOTMUCH_FIELD_PROBABILISTIC },
291 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
292 NOTMUCH_FIELD_PROBABILISTIC },
293 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
294 NOTMUCH_FIELD_PROBABILISTIC },
295 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
296 NOTMUCH_FIELD_PROBABILISTIC |
297 NOTMUCH_FIELD_PROCESSOR},
301 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
303 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
304 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
306 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
309 #if HAVE_XAPIAN_FIELD_PROCESSOR
311 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
313 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
314 Xapian::FieldProcessor *fp;
316 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
317 fp = (new DateFieldProcessor())->release ();
318 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
319 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
321 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
322 *notmuch->query_parser, notmuch))->release ();
324 /* we treat all field-processor fields as boolean in order to get the raw input */
325 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
327 _setup_query_field_default (prefix, notmuch);
332 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
334 _setup_query_field_default (prefix, notmuch);
339 _find_prefix (const char *name)
343 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
344 if (strcmp (name, prefix_table[i].name) == 0)
345 return prefix_table[i].prefix;
348 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
353 static const struct {
354 /* NOTMUCH_FEATURE_* value. */
355 _notmuch_features value;
356 /* Feature name as it appears in the database. This name should
357 * be appropriate for displaying to the user if an older version
358 * of notmuch doesn't support this feature. */
360 /* Compatibility flags when this feature is declared. */
362 } feature_names[] = {
363 { NOTMUCH_FEATURE_FILE_TERMS,
364 "multiple paths per message", "rw" },
365 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
366 "relative directory paths", "rw" },
367 /* Header values are not required for reading a database because a
368 * reader can just refer to the message file. */
369 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
370 "from/subject/message-ID in database", "w" },
371 { NOTMUCH_FEATURE_BOOL_FOLDER,
372 "exact folder:/path: search", "rw" },
373 { NOTMUCH_FEATURE_GHOSTS,
374 "mail documents for missing messages", "w"},
375 /* Knowledge of the index mime-types are not required for reading
376 * a database because a reader will just be unable to query
378 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
379 "indexed MIME types", "w"},
380 { NOTMUCH_FEATURE_LAST_MOD,
381 "modification tracking", "w"},
385 notmuch_status_to_string (notmuch_status_t status)
388 case NOTMUCH_STATUS_SUCCESS:
389 return "No error occurred";
390 case NOTMUCH_STATUS_OUT_OF_MEMORY:
391 return "Out of memory";
392 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
393 return "Attempt to write to a read-only database";
394 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
395 return "A Xapian exception occurred";
396 case NOTMUCH_STATUS_FILE_ERROR:
397 return "Something went wrong trying to read or write a file";
398 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
399 return "File is not an email";
400 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
401 return "Message ID is identical to a message in database";
402 case NOTMUCH_STATUS_NULL_POINTER:
403 return "Erroneous NULL pointer";
404 case NOTMUCH_STATUS_TAG_TOO_LONG:
405 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
406 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
407 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
408 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
409 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
410 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
411 return "Unsupported operation";
412 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
413 return "Operation requires a database upgrade";
414 case NOTMUCH_STATUS_PATH_ERROR:
415 return "Path supplied is illegal for this function";
416 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
417 return "Crypto protocol missing, malformed, or unintelligible";
418 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
419 return "Crypto engine initialization failure";
420 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
421 return "Unknown crypto protocol";
423 case NOTMUCH_STATUS_LAST_STATUS:
424 return "Unknown error status value";
429 _notmuch_database_log (notmuch_database_t *notmuch,
435 va_start (va_args, format);
437 if (notmuch->status_string)
438 talloc_free (notmuch->status_string);
440 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
445 _notmuch_database_log_append (notmuch_database_t *notmuch,
451 va_start (va_args, format);
453 if (notmuch->status_string)
454 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
456 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
462 find_doc_ids_for_term (notmuch_database_t *notmuch,
464 Xapian::PostingIterator *begin,
465 Xapian::PostingIterator *end)
467 *begin = notmuch->xapian_db->postlist_begin (term);
469 *end = notmuch->xapian_db->postlist_end (term);
473 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
474 const char *prefix_name,
476 Xapian::PostingIterator *begin,
477 Xapian::PostingIterator *end)
481 term = talloc_asprintf (notmuch, "%s%s",
482 _find_prefix (prefix_name), value);
484 find_doc_ids_for_term (notmuch, term, begin, end);
489 notmuch_private_status_t
490 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
491 const char *prefix_name,
493 unsigned int *doc_id)
495 Xapian::PostingIterator i, end;
497 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
501 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
506 #if DEBUG_DATABASE_SANITY
510 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
514 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
517 static Xapian::Document
518 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
520 return notmuch->xapian_db->get_document (doc_id);
523 /* Generate a compressed version of 'message_id' of the form:
525 * notmuch-sha1-<sha1_sum_of_message_id>
528 _notmuch_message_id_compressed (void *ctx, const char *message_id)
530 char *sha1, *compressed;
532 sha1 = _notmuch_sha1_of_string (message_id);
534 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
541 notmuch_database_find_message (notmuch_database_t *notmuch,
542 const char *message_id,
543 notmuch_message_t **message_ret)
545 notmuch_private_status_t status;
548 if (message_ret == NULL)
549 return NOTMUCH_STATUS_NULL_POINTER;
551 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
552 message_id = _notmuch_message_id_compressed (notmuch, message_id);
555 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
556 message_id, &doc_id);
558 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
561 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
563 if (*message_ret == NULL)
564 return NOTMUCH_STATUS_OUT_OF_MEMORY;
567 return NOTMUCH_STATUS_SUCCESS;
568 } catch (const Xapian::Error &error) {
569 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
570 error.get_msg().c_str());
571 notmuch->exception_reported = true;
573 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
578 notmuch_database_create (const char *path, notmuch_database_t **database)
580 char *status_string = NULL;
581 notmuch_status_t status;
583 status = notmuch_database_create_verbose (path, database,
587 fputs (status_string, stderr);
588 free (status_string);
595 notmuch_database_create_verbose (const char *path,
596 notmuch_database_t **database,
597 char **status_string)
599 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
600 notmuch_database_t *notmuch = NULL;
601 char *notmuch_path = NULL;
602 char *message = NULL;
607 message = strdup ("Error: Cannot create a database for a NULL path.\n");
608 status = NOTMUCH_STATUS_NULL_POINTER;
612 if (path[0] != '/') {
613 message = strdup ("Error: Database path must be absolute.\n");
614 status = NOTMUCH_STATUS_PATH_ERROR;
618 err = stat (path, &st);
620 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
621 path, strerror (errno)));
622 status = NOTMUCH_STATUS_FILE_ERROR;
626 if (! S_ISDIR (st.st_mode)) {
627 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
628 "Not a directory.\n",
630 status = NOTMUCH_STATUS_FILE_ERROR;
634 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
636 err = mkdir (notmuch_path, 0755);
639 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
640 notmuch_path, strerror (errno)));
641 status = NOTMUCH_STATUS_FILE_ERROR;
645 status = notmuch_database_open_verbose (path,
646 NOTMUCH_DATABASE_MODE_READ_WRITE,
651 /* Upgrade doesn't add these feature to existing databases, but
652 * new databases have them. */
653 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
654 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
656 status = notmuch_database_upgrade (notmuch, NULL, NULL);
658 notmuch_database_close(notmuch);
664 talloc_free (notmuch_path);
668 *status_string = message;
675 talloc_free (notmuch);
680 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
682 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
683 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
684 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
687 return NOTMUCH_STATUS_SUCCESS;
690 /* Allocate a revision number for the next change. */
692 _notmuch_database_new_revision (notmuch_database_t *notmuch)
694 unsigned long new_revision = notmuch->revision + 1;
696 /* If we're in an atomic section, hold off on updating the
697 * committed revision number until we commit the atomic section.
699 if (notmuch->atomic_nesting)
700 notmuch->atomic_dirty = true;
702 notmuch->revision = new_revision;
707 /* Parse a database features string from the given database version.
708 * Returns the feature bit set.
710 * For version < 3, this ignores the features string and returns a
711 * hard-coded set of features.
713 * If there are unrecognized features that are required to open the
714 * database in mode (which should be 'r' or 'w'), return a
715 * comma-separated list of unrecognized but required features in
716 * *incompat_out suitable for presenting to the user. *incompat_out
717 * will be allocated from ctx.
719 static _notmuch_features
720 _parse_features (const void *ctx, const char *features, unsigned int version,
721 char mode, char **incompat_out)
723 _notmuch_features res = static_cast<_notmuch_features>(0);
724 unsigned int namelen, i;
728 /* Prior to database version 3, features were implied by the
731 return NOTMUCH_FEATURES_V0;
732 else if (version == 1)
733 return NOTMUCH_FEATURES_V1;
734 else if (version == 2)
735 return NOTMUCH_FEATURES_V2;
737 /* Parse the features string */
738 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
739 flags = strchr (features, '\t');
740 if (! flags || flags > features + llen)
742 namelen = flags - features;
744 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
745 if (strlen (feature_names[i].name) == namelen &&
746 strncmp (feature_names[i].name, features, namelen) == 0) {
747 res |= feature_names[i].value;
752 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
753 /* Unrecognized feature */
754 const char *have = strchr (flags, mode);
755 if (have && have < features + llen) {
756 /* This feature is required to access this database in
757 * 'mode', but we don't understand it. */
759 *incompat_out = talloc_strdup (ctx, "");
760 *incompat_out = talloc_asprintf_append_buffer (
761 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
771 _print_features (const void *ctx, unsigned int features)
774 char *res = talloc_strdup (ctx, "");
776 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
777 if (features & feature_names[i].value)
778 res = talloc_asprintf_append_buffer (
779 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
785 notmuch_database_open (const char *path,
786 notmuch_database_mode_t mode,
787 notmuch_database_t **database)
789 char *status_string = NULL;
790 notmuch_status_t status;
792 status = notmuch_database_open_verbose (path, mode, database,
796 fputs (status_string, stderr);
797 free (status_string);
804 notmuch_database_open_verbose (const char *path,
805 notmuch_database_mode_t mode,
806 notmuch_database_t **database,
807 char **status_string)
809 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
810 void *local = talloc_new (NULL);
811 notmuch_database_t *notmuch = NULL;
812 char *notmuch_path, *xapian_path, *incompat_features;
813 char *message = NULL;
816 unsigned int i, version;
817 static int initialized = 0;
820 message = strdup ("Error: Cannot open a database for a NULL path.\n");
821 status = NOTMUCH_STATUS_NULL_POINTER;
825 if (path[0] != '/') {
826 message = strdup ("Error: Database path must be absolute.\n");
827 status = NOTMUCH_STATUS_PATH_ERROR;
831 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
832 message = strdup ("Out of memory\n");
833 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
837 err = stat (notmuch_path, &st);
839 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
840 notmuch_path, strerror (errno)));
841 status = NOTMUCH_STATUS_FILE_ERROR;
845 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
846 message = strdup ("Out of memory\n");
847 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
851 /* Initialize the GLib type system and threads */
852 #if !GLIB_CHECK_VERSION(2, 35, 1)
856 /* Initialize gmime */
858 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
862 notmuch = talloc_zero (NULL, notmuch_database_t);
863 notmuch->exception_reported = false;
864 notmuch->status_string = NULL;
865 notmuch->path = talloc_strdup (notmuch, path);
867 strip_trailing(notmuch->path, '/');
869 notmuch->mode = mode;
870 notmuch->atomic_nesting = 0;
873 string last_thread_id;
876 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
877 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
880 notmuch->xapian_db = new Xapian::Database (xapian_path);
883 /* Check version. As of database version 3, we represent
884 * changes in terms of features, so assume a version bump
885 * means a dramatically incompatible change. */
886 version = notmuch_database_get_version (notmuch);
887 if (version > NOTMUCH_DATABASE_VERSION) {
888 IGNORE_RESULT (asprintf (&message,
889 "Error: Notmuch database at %s\n"
890 " has a newer database format version (%u) than supported by this\n"
891 " version of notmuch (%u).\n",
892 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
893 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
894 notmuch_database_destroy (notmuch);
896 status = NOTMUCH_STATUS_FILE_ERROR;
900 /* Check features. */
901 incompat_features = NULL;
902 notmuch->features = _parse_features (
903 local, notmuch->xapian_db->get_metadata ("features").c_str (),
904 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
906 if (incompat_features) {
907 IGNORE_RESULT (asprintf (&message,
908 "Error: Notmuch database at %s\n"
909 " requires features (%s)\n"
910 " not supported by this version of notmuch.\n",
911 notmuch_path, incompat_features));
912 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
913 notmuch_database_destroy (notmuch);
915 status = NOTMUCH_STATUS_FILE_ERROR;
919 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
920 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
921 if (last_thread_id.empty ()) {
922 notmuch->last_thread_id = 0;
927 str = last_thread_id.c_str ();
928 notmuch->last_thread_id = strtoull (str, &end, 16);
930 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
933 /* Get current highest revision number. */
934 last_mod = notmuch->xapian_db->get_value_upper_bound (
935 NOTMUCH_VALUE_LAST_MOD);
936 if (last_mod.empty ())
937 notmuch->revision = 0;
939 notmuch->revision = Xapian::sortable_unserialise (last_mod);
940 notmuch->uuid = talloc_strdup (
941 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
943 notmuch->query_parser = new Xapian::QueryParser;
944 notmuch->term_gen = new Xapian::TermGenerator;
945 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
946 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
947 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
948 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
950 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
951 notmuch->query_parser->set_database (*notmuch->xapian_db);
952 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
953 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
954 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
955 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
956 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
958 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
959 const prefix_t *prefix = &prefix_table[i];
960 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
961 _setup_query_field (prefix, notmuch);
964 } catch (const Xapian::Error &error) {
965 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
966 error.get_msg().c_str()));
967 notmuch_database_destroy (notmuch);
969 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
977 *status_string = message;
985 talloc_free (notmuch);
990 notmuch_database_close (notmuch_database_t *notmuch)
992 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
994 /* Many Xapian objects (and thus notmuch objects) hold references to
995 * the database, so merely deleting the database may not suffice to
996 * close it. Thus, we explicitly close it here. */
997 if (notmuch->xapian_db != NULL) {
999 /* If there's an outstanding transaction, it's unclear if
1000 * closing the Xapian database commits everything up to
1001 * that transaction, or may discard committed (but
1002 * unflushed) transactions. To be certain, explicitly
1003 * cancel any outstanding transaction before closing. */
1004 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1005 notmuch->atomic_nesting)
1006 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1007 ->cancel_transaction ();
1009 /* Close the database. This implicitly flushes
1010 * outstanding changes. */
1011 notmuch->xapian_db->close();
1012 } catch (const Xapian::Error &error) {
1013 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1014 if (! notmuch->exception_reported) {
1015 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1016 error.get_msg().c_str());
1021 delete notmuch->term_gen;
1022 notmuch->term_gen = NULL;
1023 delete notmuch->query_parser;
1024 notmuch->query_parser = NULL;
1025 delete notmuch->xapian_db;
1026 notmuch->xapian_db = NULL;
1027 delete notmuch->value_range_processor;
1028 notmuch->value_range_processor = NULL;
1029 delete notmuch->date_range_processor;
1030 notmuch->date_range_processor = NULL;
1031 delete notmuch->last_mod_range_processor;
1032 notmuch->last_mod_range_processor = NULL;
1038 _notmuch_database_reopen (notmuch_database_t *notmuch)
1040 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1041 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1044 notmuch->xapian_db->reopen ();
1045 } catch (const Xapian::Error &error) {
1046 if (! notmuch->exception_reported) {
1047 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1048 error.get_msg ().c_str ());
1049 notmuch->exception_reported = true;
1051 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1056 return NOTMUCH_STATUS_SUCCESS;
1060 unlink_cb (const char *path,
1061 unused (const struct stat *sb),
1063 unused (struct FTW *ftw))
1065 return remove (path);
1069 rmtree (const char *path)
1071 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1074 class NotmuchCompactor : public Xapian::Compactor
1076 notmuch_compact_status_cb_t status_cb;
1077 void *status_closure;
1080 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1081 status_cb (cb), status_closure (closure) { }
1084 set_status (const std::string &table, const std::string &status)
1088 if (status_cb == NULL)
1091 if (status.length () == 0)
1092 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1094 msg = talloc_asprintf (NULL, " %s", status.c_str());
1100 status_cb (msg, status_closure);
1105 /* Compacts the given database, optionally saving the original database
1106 * in backup_path. Additionally, a callback function can be provided to
1107 * give the user feedback on the progress of the (likely long-lived)
1108 * compaction process.
1110 * The backup path must point to a directory on the same volume as the
1111 * original database. Passing a NULL backup_path will result in the
1112 * uncompacted database being deleted after compaction has finished.
1113 * Note that the database write lock will be held during the
1114 * compaction process to protect data integrity.
1117 notmuch_database_compact (const char *path,
1118 const char *backup_path,
1119 notmuch_compact_status_cb_t status_cb,
1123 char *notmuch_path, *xapian_path, *compact_xapian_path;
1124 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1125 notmuch_database_t *notmuch = NULL;
1126 struct stat statbuf;
1128 char *message = NULL;
1130 local = talloc_new (NULL);
1132 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1134 ret = notmuch_database_open_verbose (path,
1135 NOTMUCH_DATABASE_MODE_READ_WRITE,
1139 if (status_cb) status_cb (message, closure);
1143 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1144 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1148 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1149 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1153 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1154 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1158 if (backup_path == NULL) {
1159 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1160 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1163 keep_backup = false;
1169 if (stat (backup_path, &statbuf) != -1) {
1170 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1171 ret = NOTMUCH_STATUS_FILE_ERROR;
1174 if (errno != ENOENT) {
1175 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1177 ret = NOTMUCH_STATUS_FILE_ERROR;
1181 /* Unconditionally attempt to remove old work-in-progress database (if
1182 * any). This is "protected" by database lock. If this fails due to write
1183 * errors (etc), the following code will fail and provide error message.
1185 (void) rmtree (compact_xapian_path);
1188 NotmuchCompactor compactor (status_cb, closure);
1190 compactor.set_renumber (false);
1191 compactor.add_source (xapian_path);
1192 compactor.set_destdir (compact_xapian_path);
1193 compactor.compact ();
1194 } catch (const Xapian::Error &error) {
1195 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1196 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1200 if (rename (xapian_path, backup_path)) {
1201 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1202 xapian_path, backup_path, strerror (errno));
1203 ret = NOTMUCH_STATUS_FILE_ERROR;
1207 if (rename (compact_xapian_path, xapian_path)) {
1208 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1209 compact_xapian_path, xapian_path, strerror (errno));
1210 ret = NOTMUCH_STATUS_FILE_ERROR;
1214 if (! keep_backup) {
1215 if (rmtree (backup_path)) {
1216 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1217 backup_path, strerror (errno));
1218 ret = NOTMUCH_STATUS_FILE_ERROR;
1225 notmuch_status_t ret2;
1227 const char *str = notmuch_database_status_string (notmuch);
1228 if (status_cb && str)
1229 status_cb (str, closure);
1231 ret2 = notmuch_database_destroy (notmuch);
1233 /* don't clobber previous error status */
1234 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1238 talloc_free (local);
1244 notmuch_database_destroy (notmuch_database_t *notmuch)
1246 notmuch_status_t status;
1248 status = notmuch_database_close (notmuch);
1249 talloc_free (notmuch);
1255 notmuch_database_get_path (notmuch_database_t *notmuch)
1257 return notmuch->path;
1261 notmuch_database_get_version (notmuch_database_t *notmuch)
1263 unsigned int version;
1264 string version_string;
1268 version_string = notmuch->xapian_db->get_metadata ("version");
1269 if (version_string.empty ())
1272 str = version_string.c_str ();
1273 if (str == NULL || *str == '\0')
1276 version = strtoul (str, &end, 10);
1278 INTERNAL_ERROR ("Malformed database version: %s", str);
1284 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1286 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1287 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1288 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1291 static volatile sig_atomic_t do_progress_notify = 0;
1294 handle_sigalrm (unused (int signal))
1296 do_progress_notify = 1;
1299 /* Upgrade the current database.
1301 * After opening a database in read-write mode, the client should
1302 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1303 * if so, upgrade with this function before making any modifications.
1305 * The optional progress_notify callback can be used by the caller to
1306 * provide progress indication to the user. If non-NULL it will be
1307 * called periodically with 'count' as the number of messages upgraded
1308 * so far and 'total' the overall number of messages that will be
1312 notmuch_database_upgrade (notmuch_database_t *notmuch,
1313 void (*progress_notify) (void *closure,
1317 void *local = talloc_new (NULL);
1318 Xapian::TermIterator t, t_end;
1319 Xapian::WritableDatabase *db;
1320 struct sigaction action;
1321 struct itimerval timerval;
1322 bool timer_is_active = false;
1323 enum _notmuch_features target_features, new_features;
1324 notmuch_status_t status;
1325 notmuch_private_status_t private_status;
1326 notmuch_query_t *query = NULL;
1327 unsigned int count = 0, total = 0;
1329 status = _notmuch_database_ensure_writable (notmuch);
1333 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1335 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1336 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1338 if (! notmuch_database_needs_upgrade (notmuch))
1339 return NOTMUCH_STATUS_SUCCESS;
1341 if (progress_notify) {
1342 /* Set up our handler for SIGALRM */
1343 memset (&action, 0, sizeof (struct sigaction));
1344 action.sa_handler = handle_sigalrm;
1345 sigemptyset (&action.sa_mask);
1346 action.sa_flags = SA_RESTART;
1347 sigaction (SIGALRM, &action, NULL);
1349 /* Then start a timer to send SIGALRM once per second. */
1350 timerval.it_interval.tv_sec = 1;
1351 timerval.it_interval.tv_usec = 0;
1352 timerval.it_value.tv_sec = 1;
1353 timerval.it_value.tv_usec = 0;
1354 setitimer (ITIMER_REAL, &timerval, NULL);
1356 timer_is_active = true;
1359 /* Figure out how much total work we need to do. */
1361 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1362 NOTMUCH_FEATURE_LAST_MOD)) {
1363 query = notmuch_query_create (notmuch, "");
1366 status = notmuch_query_count_messages (query, &msg_count);
1371 notmuch_query_destroy (query);
1374 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1375 t_end = db->allterms_end ("XTIMESTAMP");
1376 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1379 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1380 /* The ghost message upgrade converts all thread_id_*
1381 * metadata values into ghost message documents. */
1382 t_end = db->metadata_keys_end ("thread_id_");
1383 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1387 /* Perform the upgrade in a transaction. */
1388 db->begin_transaction (true);
1390 /* Set the target features so we write out changes in the desired
1392 notmuch->features = target_features;
1394 /* Perform per-message upgrades. */
1396 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1397 NOTMUCH_FEATURE_LAST_MOD)) {
1398 notmuch_messages_t *messages;
1399 notmuch_message_t *message;
1402 query = notmuch_query_create (notmuch, "");
1404 status = notmuch_query_search_messages (query, &messages);
1408 notmuch_messages_valid (messages);
1409 notmuch_messages_move_to_next (messages))
1411 if (do_progress_notify) {
1412 progress_notify (closure, (double) count / total);
1413 do_progress_notify = 0;
1416 message = notmuch_messages_get (messages);
1418 /* Before version 1, each message document had its
1419 * filename in the data field. Copy that into the new
1420 * format by calling notmuch_message_add_filename.
1422 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1423 filename = _notmuch_message_talloc_copy_data (message);
1424 if (filename && *filename != '\0') {
1425 _notmuch_message_add_filename (message, filename);
1426 _notmuch_message_clear_data (message);
1428 talloc_free (filename);
1431 /* Prior to version 2, the "folder:" prefix was
1432 * probabilistic and stemmed. Change it to the current
1433 * boolean prefix. Add "path:" prefixes while at it.
1435 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1436 _notmuch_message_upgrade_folder (message);
1438 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1439 * track modification revisions. Give all messages the
1440 * next available revision; since we just started tracking
1441 * revisions for this database, that will be 1.
1443 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1444 _notmuch_message_upgrade_last_mod (message);
1446 _notmuch_message_sync (message);
1448 notmuch_message_destroy (message);
1453 notmuch_query_destroy (query);
1457 /* Perform per-directory upgrades. */
1459 /* Before version 1 we stored directory timestamps in
1460 * XTIMESTAMP documents instead of the current XDIRECTORY
1461 * documents. So copy those as well. */
1462 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1463 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1465 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1469 Xapian::PostingIterator p, p_end;
1470 std::string term = *t;
1472 p_end = notmuch->xapian_db->postlist_end (term);
1474 for (p = notmuch->xapian_db->postlist_begin (term);
1478 Xapian::Document document;
1480 notmuch_directory_t *directory;
1482 if (do_progress_notify) {
1483 progress_notify (closure, (double) count / total);
1484 do_progress_notify = 0;
1487 document = find_document_for_doc_id (notmuch, *p);
1488 mtime = Xapian::sortable_unserialise (
1489 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1491 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1492 NOTMUCH_FIND_CREATE, &status);
1493 notmuch_directory_set_mtime (directory, mtime);
1494 notmuch_directory_destroy (directory);
1496 db->delete_document (*p);
1503 /* Perform metadata upgrades. */
1505 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1506 * messages were stored as database metadata. Change these to
1509 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1510 notmuch_message_t *message;
1511 std::string message_id, thread_id;
1513 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1514 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1516 if (do_progress_notify) {
1517 progress_notify (closure, (double) count / total);
1518 do_progress_notify = 0;
1521 message_id = (*t).substr (
1522 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1523 thread_id = db->get_metadata (*t);
1525 /* Create ghost message */
1526 message = _notmuch_message_create_for_message_id (
1527 notmuch, message_id.c_str (), &private_status);
1528 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1529 /* Document already exists; ignore the stored thread ID */
1530 } else if (private_status ==
1531 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1532 private_status = _notmuch_message_initialize_ghost (
1533 message, thread_id.c_str ());
1534 if (! private_status)
1535 _notmuch_message_sync (message);
1538 if (private_status) {
1539 _notmuch_database_log (notmuch,
1540 "Upgrade failed while creating ghost messages.\n");
1541 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1545 /* Clear saved metadata thread ID */
1546 db->set_metadata (*t, "");
1552 status = NOTMUCH_STATUS_SUCCESS;
1553 db->set_metadata ("features", _print_features (local, notmuch->features));
1554 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1557 if (status == NOTMUCH_STATUS_SUCCESS)
1558 db->commit_transaction ();
1560 db->cancel_transaction ();
1562 if (timer_is_active) {
1563 /* Now stop the timer. */
1564 timerval.it_interval.tv_sec = 0;
1565 timerval.it_interval.tv_usec = 0;
1566 timerval.it_value.tv_sec = 0;
1567 timerval.it_value.tv_usec = 0;
1568 setitimer (ITIMER_REAL, &timerval, NULL);
1570 /* And disable the signal handler. */
1571 action.sa_handler = SIG_IGN;
1572 sigaction (SIGALRM, &action, NULL);
1576 notmuch_query_destroy (query);
1578 talloc_free (local);
1583 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1585 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1586 notmuch->atomic_nesting > 0)
1589 if (notmuch_database_needs_upgrade (notmuch))
1590 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1593 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1594 } catch (const Xapian::Error &error) {
1595 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1596 error.get_msg().c_str());
1597 notmuch->exception_reported = true;
1598 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1602 notmuch->atomic_nesting++;
1603 return NOTMUCH_STATUS_SUCCESS;
1607 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1609 Xapian::WritableDatabase *db;
1611 if (notmuch->atomic_nesting == 0)
1612 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1614 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1615 notmuch->atomic_nesting > 1)
1618 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1620 db->commit_transaction ();
1622 /* This is a hack for testing. Xapian never flushes on a
1623 * non-flushed commit, even if the flush threshold is 1.
1624 * However, we rely on flushing to test atomicity. */
1625 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1626 if (thresh && atoi (thresh) == 1)
1628 } catch (const Xapian::Error &error) {
1629 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1630 error.get_msg().c_str());
1631 notmuch->exception_reported = true;
1632 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1635 if (notmuch->atomic_dirty) {
1636 ++notmuch->revision;
1637 notmuch->atomic_dirty = false;
1641 notmuch->atomic_nesting--;
1642 return NOTMUCH_STATUS_SUCCESS;
1646 notmuch_database_get_revision (notmuch_database_t *notmuch,
1650 *uuid = notmuch->uuid;
1651 return notmuch->revision;
1654 /* We allow the user to use arbitrarily long paths for directories. But
1655 * we have a term-length limit. So if we exceed that, we'll use the
1656 * SHA-1 of the path for the database term.
1658 * Note: This function may return the original value of 'path'. If it
1659 * does not, then the caller is responsible to free() the returned
1663 _notmuch_database_get_directory_db_path (const char *path)
1665 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1667 if (term_len > NOTMUCH_TERM_MAX)
1668 return _notmuch_sha1_of_string (path);
1673 /* Given a path, split it into two parts: the directory part is all
1674 * components except for the last, and the basename is that last
1675 * component. Getting the return-value for either part is optional
1676 * (the caller can pass NULL).
1678 * The original 'path' can represent either a regular file or a
1679 * directory---the splitting will be carried out in the same way in
1680 * either case. Trailing slashes on 'path' will be ignored, and any
1681 * cases of multiple '/' characters appearing in series will be
1682 * treated as a single '/'.
1684 * Allocation (if any) will have 'ctx' as the talloc owner. But
1685 * pointers will be returned within the original path string whenever
1688 * Note: If 'path' is non-empty and contains no non-trailing slash,
1689 * (that is, consists of a filename with no parent directory), then
1690 * the directory returned will be an empty string. However, if 'path'
1691 * is an empty string, then both directory and basename will be
1695 _notmuch_database_split_path (void *ctx,
1697 const char **directory,
1698 const char **basename)
1702 if (path == NULL || *path == '\0') {
1707 return NOTMUCH_STATUS_SUCCESS;
1710 /* Find the last slash (not counting a trailing slash), if any. */
1712 slash = path + strlen (path) - 1;
1714 /* First, skip trailing slashes. */
1715 while (slash != path && *slash == '/')
1718 /* Then, find a slash. */
1719 while (slash != path && *slash != '/') {
1726 /* Finally, skip multiple slashes. */
1727 while (slash != path && *(slash - 1) == '/')
1730 if (slash == path) {
1732 *directory = talloc_strdup (ctx, "");
1737 *directory = talloc_strndup (ctx, path, slash - path);
1740 return NOTMUCH_STATUS_SUCCESS;
1743 /* Find the document ID of the specified directory.
1745 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1746 * created if one does not exist for 'path'. Otherwise, if the
1747 * directory document does not exist, this sets *directory_id to
1748 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1751 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1753 notmuch_find_flags_t flags,
1754 unsigned int *directory_id)
1756 notmuch_directory_t *directory;
1757 notmuch_status_t status;
1761 return NOTMUCH_STATUS_SUCCESS;
1764 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1765 if (status || !directory) {
1770 *directory_id = _notmuch_directory_get_document_id (directory);
1772 notmuch_directory_destroy (directory);
1774 return NOTMUCH_STATUS_SUCCESS;
1778 _notmuch_database_get_directory_path (void *ctx,
1779 notmuch_database_t *notmuch,
1780 unsigned int doc_id)
1782 Xapian::Document document;
1784 document = find_document_for_doc_id (notmuch, doc_id);
1786 return talloc_strdup (ctx, document.get_data ().c_str ());
1789 /* Given a legal 'filename' for the database, (either relative to
1790 * database path or absolute with initial components identical to
1791 * database path), return a new string (with 'ctx' as the talloc
1792 * owner) suitable for use as a direntry term value.
1794 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1795 * will be created in the database as needed. Otherwise, if the
1796 * necessary directory documents do not exist, this sets
1797 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1800 _notmuch_database_filename_to_direntry (void *ctx,
1801 notmuch_database_t *notmuch,
1802 const char *filename,
1803 notmuch_find_flags_t flags,
1806 const char *relative, *directory, *basename;
1807 Xapian::docid directory_id;
1808 notmuch_status_t status;
1810 relative = _notmuch_database_relative_path (notmuch, filename);
1812 status = _notmuch_database_split_path (ctx, relative,
1813 &directory, &basename);
1817 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1819 if (status || directory_id == (unsigned int)-1) {
1824 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1826 return NOTMUCH_STATUS_SUCCESS;
1829 /* Given a legal 'path' for the database, return the relative path.
1831 * The return value will be a pointer to the original path contents,
1832 * and will be either the original string (if 'path' was relative) or
1833 * a portion of the string (if path was absolute and begins with the
1837 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1840 const char *db_path, *relative;
1841 unsigned int db_path_len;
1843 db_path = notmuch_database_get_path (notmuch);
1844 db_path_len = strlen (db_path);
1848 if (*relative == '/') {
1849 while (*relative == '/' && *(relative+1) == '/')
1852 if (strncmp (relative, db_path, db_path_len) == 0)
1854 relative += db_path_len;
1855 while (*relative == '/')
1864 notmuch_database_get_directory (notmuch_database_t *notmuch,
1866 notmuch_directory_t **directory)
1868 notmuch_status_t status;
1870 if (directory == NULL)
1871 return NOTMUCH_STATUS_NULL_POINTER;
1875 *directory = _notmuch_directory_create (notmuch, path,
1876 NOTMUCH_FIND_LOOKUP, &status);
1877 } catch (const Xapian::Error &error) {
1878 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1879 error.get_msg().c_str());
1880 notmuch->exception_reported = true;
1881 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1886 /* Allocate a document ID that satisfies the following criteria:
1888 * 1. The ID does not exist for any document in the Xapian database
1890 * 2. The ID was not previously returned from this function
1892 * 3. The ID is the smallest integer satisfying (1) and (2)
1894 * This function will trigger an internal error if these constraints
1895 * cannot all be satisfied, (that is, the pool of available document
1896 * IDs has been exhausted).
1899 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1901 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1903 notmuch->last_doc_id++;
1905 if (notmuch->last_doc_id == 0)
1906 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1908 return notmuch->last_doc_id;
1912 notmuch_database_remove_message (notmuch_database_t *notmuch,
1913 const char *filename)
1915 notmuch_status_t status;
1916 notmuch_message_t *message;
1918 status = notmuch_database_find_message_by_filename (notmuch, filename,
1921 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1922 status = _notmuch_message_remove_filename (message, filename);
1923 if (status == NOTMUCH_STATUS_SUCCESS)
1924 _notmuch_message_delete (message);
1925 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1926 _notmuch_message_sync (message);
1928 notmuch_message_destroy (message);
1935 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1936 const char *filename,
1937 notmuch_message_t **message_ret)
1940 const char *prefix = _find_prefix ("file-direntry");
1941 char *direntry, *term;
1942 Xapian::PostingIterator i, end;
1943 notmuch_status_t status;
1945 if (message_ret == NULL)
1946 return NOTMUCH_STATUS_NULL_POINTER;
1948 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1949 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1951 /* return NULL on any failure */
1952 *message_ret = NULL;
1954 local = talloc_new (notmuch);
1957 status = _notmuch_database_filename_to_direntry (
1958 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1959 if (status || !direntry)
1962 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1964 find_doc_ids_for_term (notmuch, term, &i, &end);
1967 notmuch_private_status_t private_status;
1969 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1971 if (*message_ret == NULL)
1972 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1974 } catch (const Xapian::Error &error) {
1975 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1976 error.get_msg().c_str());
1977 notmuch->exception_reported = true;
1978 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1982 talloc_free (local);
1984 if (status && *message_ret) {
1985 notmuch_message_destroy (*message_ret);
1986 *message_ret = NULL;
1991 notmuch_string_list_t *
1992 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1993 Xapian::TermIterator &end,
1996 int prefix_len = strlen (prefix);
1997 notmuch_string_list_t *list;
1999 list = _notmuch_string_list_create (ctx);
2000 if (unlikely (list == NULL))
2003 for (i.skip_to (prefix); i != end; i++) {
2004 /* Terminate loop at first term without desired prefix. */
2005 if (strncmp ((*i).c_str (), prefix, prefix_len))
2008 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2015 notmuch_database_get_all_tags (notmuch_database_t *db)
2017 Xapian::TermIterator i, end;
2018 notmuch_string_list_t *tags;
2021 i = db->xapian_db->allterms_begin();
2022 end = db->xapian_db->allterms_end();
2023 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2024 _find_prefix ("tag"));
2025 _notmuch_string_list_sort (tags);
2026 return _notmuch_tags_create (db, tags);
2027 } catch (const Xapian::Error &error) {
2028 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2029 error.get_msg().c_str());
2030 db->exception_reported = true;
2036 notmuch_database_status_string (const notmuch_database_t *notmuch)
2038 return notmuch->status_string;