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
127 * user in searching. Similarly, terms from the path of the mail
128 * message are added with "folder" and "path" prefixes. But the
129 * database doesn't really care itself about any of these.
131 * The data portion of a mail document is empty.
133 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
134 * -----------------------------------------------
135 * A ghost mail document is like a mail document, but where we don't
136 * have the message content. These are used to track thread reference
137 * information for messages we haven't received.
139 * A ghost mail document has type: ghost; id and thread fields that
140 * are identical to the mail document fields; and a MESSAGE_ID value.
144 * A directory document is used by a client of the notmuch library to
145 * maintain data necessary to allow for efficient polling of mail
148 * All directory documents contain one term:
150 * directory: The directory path (relative to the database path)
151 * Or the SHA1 sum of the directory path (if the
152 * path itself is too long to fit in a Xapian
155 * And all directory documents for directories other than top-level
156 * directories also contain the following term:
158 * directory-direntry: A colon-separated pair of values
159 * (INTEGER:STRING), where INTEGER is the
160 * document ID of the parent directory
161 * document, and STRING is the name of this
162 * directory within that parent.
164 * All directory documents have a single value:
166 * TIMESTAMP: The mtime of the directory (at last scan)
168 * The data portion of a directory document contains the path of the
169 * directory (relative to the database path).
173 * Xapian allows us to store arbitrary name-value pairs as
174 * "metadata". We currently use the following metadata names with the
177 * version The database schema version, (which is distinct
178 * from both the notmuch package version (see
179 * notmuch --version) and the libnotmuch library
180 * version. The version is stored as an base-10
181 * ASCII integer. The initial database version
182 * was 1, (though a schema existed before that
183 * were no "version" database value existed at
184 * all). Successive versions are allocated as
185 * changes are made to the database (such as by
186 * indexing new fields).
188 * features The set of features supported by this
189 * database. This consists of a set of
190 * '\n'-separated lines, where each is a feature
191 * name, a '\t', and compatibility flags. If the
192 * compatibility flags contain 'w', then the
193 * opener must support this feature to safely
194 * write this database. If the compatibility
195 * flags contain 'r', then the opener must
196 * support this feature to read this database.
197 * Introduced in database version 3.
199 * last_thread_id The last thread ID generated. This is stored
200 * as a 16-byte hexadecimal ASCII representation
201 * of a 64-bit unsigned integer. The first ID
202 * generated is 1 and the value will be
203 * incremented for each thread ID.
205 * C* metadata keys starting with C indicate
206 * configuration data. It can be managed with the
207 * n_database_*config* API. There is a convention
208 * of hierarchical keys separated by '.' (e.g.
209 * query.notmuch stores the value for the named
210 * query 'notmuch'), but it is not enforced by the
216 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
217 * Instead, the database has the following additional database
220 * thread_id_* A pre-allocated thread ID for a particular
221 * message. This is actually an arbitrarily large
222 * family of metadata name. Any particular name is
223 * formed by concatenating "thread_id_" with a message
224 * ID (or the SHA1 sum of a message ID if it is very
225 * long---see description of 'id' in the mail
226 * document). The value stored is a thread ID.
228 * These thread ID metadata values are stored
229 * whenever a message references a parent message
230 * that does not yet exist in the database. A
231 * thread ID will be allocated and stored, and if
232 * the message is later added, the stored thread
233 * ID will be used (and the metadata value will
236 * Even before a message is added, it's
237 * pre-allocated thread ID is useful so that all
238 * descendant messages that reference this common
239 * parent can be recognized as belonging to the
243 /* With these prefix values we follow the conventions published here:
245 * https://xapian.org/docs/omega/termprefixes.html
247 * as much as makes sense. Note that I took some liberty in matching
248 * the reserved prefix values to notmuch concepts, (for example, 'G'
249 * is documented as "newsGroup (or similar entity - e.g. a web forum
250 * name)", for which I think the thread is the closest analogue in
251 * notmuch. This in spite of the fact that we will eventually be
252 * storing mailing-list messages where 'G' for "mailing list name"
253 * might be even a closer analogue. I'm treating the single-character
254 * prefixes preferentially for core notmuch concepts (which will be
255 * nearly universal to all mail messages).
259 prefix_t prefix_table[] = {
260 /* name term prefix flags */
261 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
262 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
263 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
264 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
265 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
266 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
267 { "thread", "G", NOTMUCH_FIELD_EXTERNAL |
268 NOTMUCH_FIELD_PROCESSOR },
269 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
270 NOTMUCH_FIELD_PROCESSOR },
271 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
272 NOTMUCH_FIELD_PROCESSOR },
273 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
274 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
275 NOTMUCH_FIELD_PROCESSOR },
276 { "path", "P", NOTMUCH_FIELD_EXTERNAL|
277 NOTMUCH_FIELD_PROCESSOR },
278 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
280 * Unconditionally add ':' to reduce potential ambiguity with
281 * overlapping prefixes and/or terms that start with capital
282 * letters. See Xapian document termprefixes.html for related
285 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
286 NOTMUCH_FIELD_PROCESSOR },
287 #if HAVE_XAPIAN_FIELD_PROCESSOR
288 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
289 NOTMUCH_FIELD_PROCESSOR },
290 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
291 NOTMUCH_FIELD_PROCESSOR },
293 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
294 NOTMUCH_FIELD_PROBABILISTIC |
295 NOTMUCH_FIELD_PROCESSOR },
296 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
297 NOTMUCH_FIELD_PROBABILISTIC },
298 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
299 NOTMUCH_FIELD_PROBABILISTIC },
300 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
301 NOTMUCH_FIELD_PROBABILISTIC },
302 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
303 NOTMUCH_FIELD_PROBABILISTIC |
304 NOTMUCH_FIELD_PROCESSOR},
308 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
310 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
311 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
313 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
316 #if HAVE_XAPIAN_FIELD_PROCESSOR
318 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
320 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
321 Xapian::FieldProcessor *fp;
323 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
324 fp = (new DateFieldProcessor())->release ();
325 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
326 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
327 else if (STRNCMP_LITERAL(prefix->name, "thread") == 0)
328 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
330 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
331 *notmuch->query_parser, notmuch))->release ();
333 /* we treat all field-processor fields as boolean in order to get the raw input */
334 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
336 _setup_query_field_default (prefix, notmuch);
341 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
343 _setup_query_field_default (prefix, notmuch);
348 _find_prefix (const char *name)
352 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
353 if (strcmp (name, prefix_table[i].name) == 0)
354 return prefix_table[i].prefix;
357 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
362 static const struct {
363 /* NOTMUCH_FEATURE_* value. */
364 _notmuch_features value;
365 /* Feature name as it appears in the database. This name should
366 * be appropriate for displaying to the user if an older version
367 * of notmuch doesn't support this feature. */
369 /* Compatibility flags when this feature is declared. */
371 } feature_names[] = {
372 { NOTMUCH_FEATURE_FILE_TERMS,
373 "multiple paths per message", "rw" },
374 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
375 "relative directory paths", "rw" },
376 /* Header values are not required for reading a database because a
377 * reader can just refer to the message file. */
378 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
379 "from/subject/message-ID in database", "w" },
380 { NOTMUCH_FEATURE_BOOL_FOLDER,
381 "exact folder:/path: search", "rw" },
382 { NOTMUCH_FEATURE_GHOSTS,
383 "mail documents for missing messages", "w"},
384 /* Knowledge of the index mime-types are not required for reading
385 * a database because a reader will just be unable to query
387 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
388 "indexed MIME types", "w"},
389 { NOTMUCH_FEATURE_LAST_MOD,
390 "modification tracking", "w"},
394 notmuch_status_to_string (notmuch_status_t status)
397 case NOTMUCH_STATUS_SUCCESS:
398 return "No error occurred";
399 case NOTMUCH_STATUS_OUT_OF_MEMORY:
400 return "Out of memory";
401 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
402 return "Attempt to write to a read-only database";
403 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
404 return "A Xapian exception occurred";
405 case NOTMUCH_STATUS_FILE_ERROR:
406 return "Something went wrong trying to read or write a file";
407 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
408 return "File is not an email";
409 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
410 return "Message ID is identical to a message in database";
411 case NOTMUCH_STATUS_NULL_POINTER:
412 return "Erroneous NULL pointer";
413 case NOTMUCH_STATUS_TAG_TOO_LONG:
414 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
415 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
416 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
417 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
418 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
419 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
420 return "Unsupported operation";
421 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
422 return "Operation requires a database upgrade";
423 case NOTMUCH_STATUS_PATH_ERROR:
424 return "Path supplied is illegal for this function";
425 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
426 return "Crypto protocol missing, malformed, or unintelligible";
427 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
428 return "Crypto engine initialization failure";
429 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
430 return "Unknown crypto protocol";
432 case NOTMUCH_STATUS_LAST_STATUS:
433 return "Unknown error status value";
438 _notmuch_database_log (notmuch_database_t *notmuch,
444 va_start (va_args, format);
446 if (notmuch->status_string)
447 talloc_free (notmuch->status_string);
449 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
454 _notmuch_database_log_append (notmuch_database_t *notmuch,
460 va_start (va_args, format);
462 if (notmuch->status_string)
463 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
465 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
471 find_doc_ids_for_term (notmuch_database_t *notmuch,
473 Xapian::PostingIterator *begin,
474 Xapian::PostingIterator *end)
476 *begin = notmuch->xapian_db->postlist_begin (term);
478 *end = notmuch->xapian_db->postlist_end (term);
482 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
483 const char *prefix_name,
485 Xapian::PostingIterator *begin,
486 Xapian::PostingIterator *end)
490 term = talloc_asprintf (notmuch, "%s%s",
491 _find_prefix (prefix_name), value);
493 find_doc_ids_for_term (notmuch, term, begin, end);
498 notmuch_private_status_t
499 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
500 const char *prefix_name,
502 unsigned int *doc_id)
504 Xapian::PostingIterator i, end;
506 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
510 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
515 #if DEBUG_DATABASE_SANITY
519 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
523 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
526 static Xapian::Document
527 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
529 return notmuch->xapian_db->get_document (doc_id);
532 /* Generate a compressed version of 'message_id' of the form:
534 * notmuch-sha1-<sha1_sum_of_message_id>
537 _notmuch_message_id_compressed (void *ctx, const char *message_id)
539 char *sha1, *compressed;
541 sha1 = _notmuch_sha1_of_string (message_id);
543 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
550 notmuch_database_find_message (notmuch_database_t *notmuch,
551 const char *message_id,
552 notmuch_message_t **message_ret)
554 notmuch_private_status_t status;
557 if (message_ret == NULL)
558 return NOTMUCH_STATUS_NULL_POINTER;
560 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
561 message_id = _notmuch_message_id_compressed (notmuch, message_id);
564 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
565 message_id, &doc_id);
567 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
570 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
572 if (*message_ret == NULL)
573 return NOTMUCH_STATUS_OUT_OF_MEMORY;
576 return NOTMUCH_STATUS_SUCCESS;
577 } catch (const Xapian::Error &error) {
578 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
579 error.get_msg().c_str());
580 notmuch->exception_reported = true;
582 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
587 notmuch_database_create (const char *path, notmuch_database_t **database)
589 char *status_string = NULL;
590 notmuch_status_t status;
592 status = notmuch_database_create_verbose (path, database,
596 fputs (status_string, stderr);
597 free (status_string);
604 notmuch_database_create_verbose (const char *path,
605 notmuch_database_t **database,
606 char **status_string)
608 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
609 notmuch_database_t *notmuch = NULL;
610 char *notmuch_path = NULL;
611 char *message = NULL;
616 message = strdup ("Error: Cannot create a database for a NULL path.\n");
617 status = NOTMUCH_STATUS_NULL_POINTER;
621 if (path[0] != '/') {
622 message = strdup ("Error: Database path must be absolute.\n");
623 status = NOTMUCH_STATUS_PATH_ERROR;
627 err = stat (path, &st);
629 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
630 path, strerror (errno)));
631 status = NOTMUCH_STATUS_FILE_ERROR;
635 if (! S_ISDIR (st.st_mode)) {
636 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
637 "Not a directory.\n",
639 status = NOTMUCH_STATUS_FILE_ERROR;
643 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
645 err = mkdir (notmuch_path, 0755);
648 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
649 notmuch_path, strerror (errno)));
650 status = NOTMUCH_STATUS_FILE_ERROR;
654 status = notmuch_database_open_verbose (path,
655 NOTMUCH_DATABASE_MODE_READ_WRITE,
660 /* Upgrade doesn't add these feature to existing databases, but
661 * new databases have them. */
662 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
663 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
665 status = notmuch_database_upgrade (notmuch, NULL, NULL);
667 notmuch_database_close(notmuch);
673 talloc_free (notmuch_path);
677 *status_string = message;
684 talloc_free (notmuch);
689 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
691 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
692 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
693 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
696 return NOTMUCH_STATUS_SUCCESS;
699 /* Allocate a revision number for the next change. */
701 _notmuch_database_new_revision (notmuch_database_t *notmuch)
703 unsigned long new_revision = notmuch->revision + 1;
705 /* If we're in an atomic section, hold off on updating the
706 * committed revision number until we commit the atomic section.
708 if (notmuch->atomic_nesting)
709 notmuch->atomic_dirty = true;
711 notmuch->revision = new_revision;
716 /* Parse a database features string from the given database version.
717 * Returns the feature bit set.
719 * For version < 3, this ignores the features string and returns a
720 * hard-coded set of features.
722 * If there are unrecognized features that are required to open the
723 * database in mode (which should be 'r' or 'w'), return a
724 * comma-separated list of unrecognized but required features in
725 * *incompat_out suitable for presenting to the user. *incompat_out
726 * will be allocated from ctx.
728 static _notmuch_features
729 _parse_features (const void *ctx, const char *features, unsigned int version,
730 char mode, char **incompat_out)
732 _notmuch_features res = static_cast<_notmuch_features>(0);
733 unsigned int namelen, i;
737 /* Prior to database version 3, features were implied by the
740 return NOTMUCH_FEATURES_V0;
741 else if (version == 1)
742 return NOTMUCH_FEATURES_V1;
743 else if (version == 2)
744 return NOTMUCH_FEATURES_V2;
746 /* Parse the features string */
747 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
748 flags = strchr (features, '\t');
749 if (! flags || flags > features + llen)
751 namelen = flags - features;
753 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
754 if (strlen (feature_names[i].name) == namelen &&
755 strncmp (feature_names[i].name, features, namelen) == 0) {
756 res |= feature_names[i].value;
761 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
762 /* Unrecognized feature */
763 const char *have = strchr (flags, mode);
764 if (have && have < features + llen) {
765 /* This feature is required to access this database in
766 * 'mode', but we don't understand it. */
768 *incompat_out = talloc_strdup (ctx, "");
769 *incompat_out = talloc_asprintf_append_buffer (
770 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
780 _print_features (const void *ctx, unsigned int features)
783 char *res = talloc_strdup (ctx, "");
785 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
786 if (features & feature_names[i].value)
787 res = talloc_asprintf_append_buffer (
788 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
794 notmuch_database_open (const char *path,
795 notmuch_database_mode_t mode,
796 notmuch_database_t **database)
798 char *status_string = NULL;
799 notmuch_status_t status;
801 status = notmuch_database_open_verbose (path, mode, database,
805 fputs (status_string, stderr);
806 free (status_string);
813 notmuch_database_open_verbose (const char *path,
814 notmuch_database_mode_t mode,
815 notmuch_database_t **database,
816 char **status_string)
818 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
819 void *local = talloc_new (NULL);
820 notmuch_database_t *notmuch = NULL;
821 char *notmuch_path, *xapian_path, *incompat_features;
822 char *message = NULL;
825 unsigned int i, version;
826 static int initialized = 0;
829 message = strdup ("Error: Cannot open a database for a NULL path.\n");
830 status = NOTMUCH_STATUS_NULL_POINTER;
834 if (path[0] != '/') {
835 message = strdup ("Error: Database path must be absolute.\n");
836 status = NOTMUCH_STATUS_PATH_ERROR;
840 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
841 message = strdup ("Out of memory\n");
842 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
846 err = stat (notmuch_path, &st);
848 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
849 notmuch_path, strerror (errno)));
850 status = NOTMUCH_STATUS_FILE_ERROR;
854 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
855 message = strdup ("Out of memory\n");
856 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
860 /* Initialize the GLib type system and threads */
861 #if !GLIB_CHECK_VERSION(2, 35, 1)
865 /* Initialize gmime */
867 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
871 notmuch = talloc_zero (NULL, notmuch_database_t);
872 notmuch->exception_reported = false;
873 notmuch->status_string = NULL;
874 notmuch->path = talloc_strdup (notmuch, path);
876 strip_trailing(notmuch->path, '/');
878 notmuch->mode = mode;
879 notmuch->atomic_nesting = 0;
882 string last_thread_id;
885 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
886 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
889 notmuch->xapian_db = new Xapian::Database (xapian_path);
892 /* Check version. As of database version 3, we represent
893 * changes in terms of features, so assume a version bump
894 * means a dramatically incompatible change. */
895 version = notmuch_database_get_version (notmuch);
896 if (version > NOTMUCH_DATABASE_VERSION) {
897 IGNORE_RESULT (asprintf (&message,
898 "Error: Notmuch database at %s\n"
899 " has a newer database format version (%u) than supported by this\n"
900 " version of notmuch (%u).\n",
901 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
902 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
903 notmuch_database_destroy (notmuch);
905 status = NOTMUCH_STATUS_FILE_ERROR;
909 /* Check features. */
910 incompat_features = NULL;
911 notmuch->features = _parse_features (
912 local, notmuch->xapian_db->get_metadata ("features").c_str (),
913 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
915 if (incompat_features) {
916 IGNORE_RESULT (asprintf (&message,
917 "Error: Notmuch database at %s\n"
918 " requires features (%s)\n"
919 " not supported by this version of notmuch.\n",
920 notmuch_path, incompat_features));
921 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
922 notmuch_database_destroy (notmuch);
924 status = NOTMUCH_STATUS_FILE_ERROR;
928 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
929 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
930 if (last_thread_id.empty ()) {
931 notmuch->last_thread_id = 0;
936 str = last_thread_id.c_str ();
937 notmuch->last_thread_id = strtoull (str, &end, 16);
939 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
942 /* Get current highest revision number. */
943 last_mod = notmuch->xapian_db->get_value_upper_bound (
944 NOTMUCH_VALUE_LAST_MOD);
945 if (last_mod.empty ())
946 notmuch->revision = 0;
948 notmuch->revision = Xapian::sortable_unserialise (last_mod);
949 notmuch->uuid = talloc_strdup (
950 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
952 notmuch->query_parser = new Xapian::QueryParser;
953 notmuch->term_gen = new Xapian::TermGenerator;
954 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
955 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
956 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
957 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
959 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
960 notmuch->query_parser->set_database (*notmuch->xapian_db);
961 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
962 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
963 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
964 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
965 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
967 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
968 const prefix_t *prefix = &prefix_table[i];
969 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
970 _setup_query_field (prefix, notmuch);
973 } catch (const Xapian::Error &error) {
974 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
975 error.get_msg().c_str()));
976 notmuch_database_destroy (notmuch);
978 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
986 *status_string = message;
994 talloc_free (notmuch);
999 notmuch_database_close (notmuch_database_t *notmuch)
1001 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1003 /* Many Xapian objects (and thus notmuch objects) hold references to
1004 * the database, so merely deleting the database may not suffice to
1005 * close it. Thus, we explicitly close it here. */
1006 if (notmuch->xapian_db != NULL) {
1008 /* If there's an outstanding transaction, it's unclear if
1009 * closing the Xapian database commits everything up to
1010 * that transaction, or may discard committed (but
1011 * unflushed) transactions. To be certain, explicitly
1012 * cancel any outstanding transaction before closing. */
1013 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1014 notmuch->atomic_nesting)
1015 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1016 ->cancel_transaction ();
1018 /* Close the database. This implicitly flushes
1019 * outstanding changes. */
1020 notmuch->xapian_db->close();
1021 } catch (const Xapian::Error &error) {
1022 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1023 if (! notmuch->exception_reported) {
1024 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1025 error.get_msg().c_str());
1030 delete notmuch->term_gen;
1031 notmuch->term_gen = NULL;
1032 delete notmuch->query_parser;
1033 notmuch->query_parser = NULL;
1034 delete notmuch->xapian_db;
1035 notmuch->xapian_db = NULL;
1036 delete notmuch->value_range_processor;
1037 notmuch->value_range_processor = NULL;
1038 delete notmuch->date_range_processor;
1039 notmuch->date_range_processor = NULL;
1040 delete notmuch->last_mod_range_processor;
1041 notmuch->last_mod_range_processor = NULL;
1047 _notmuch_database_reopen (notmuch_database_t *notmuch)
1049 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1050 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1053 notmuch->xapian_db->reopen ();
1054 } catch (const Xapian::Error &error) {
1055 if (! notmuch->exception_reported) {
1056 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1057 error.get_msg ().c_str ());
1058 notmuch->exception_reported = true;
1060 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1065 return NOTMUCH_STATUS_SUCCESS;
1069 unlink_cb (const char *path,
1070 unused (const struct stat *sb),
1072 unused (struct FTW *ftw))
1074 return remove (path);
1078 rmtree (const char *path)
1080 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1083 class NotmuchCompactor : public Xapian::Compactor
1085 notmuch_compact_status_cb_t status_cb;
1086 void *status_closure;
1089 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1090 status_cb (cb), status_closure (closure) { }
1093 set_status (const std::string &table, const std::string &status)
1097 if (status_cb == NULL)
1100 if (status.length () == 0)
1101 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1103 msg = talloc_asprintf (NULL, " %s", status.c_str());
1109 status_cb (msg, status_closure);
1114 /* Compacts the given database, optionally saving the original database
1115 * in backup_path. Additionally, a callback function can be provided to
1116 * give the user feedback on the progress of the (likely long-lived)
1117 * compaction process.
1119 * The backup path must point to a directory on the same volume as the
1120 * original database. Passing a NULL backup_path will result in the
1121 * uncompacted database being deleted after compaction has finished.
1122 * Note that the database write lock will be held during the
1123 * compaction process to protect data integrity.
1126 notmuch_database_compact (const char *path,
1127 const char *backup_path,
1128 notmuch_compact_status_cb_t status_cb,
1132 char *notmuch_path, *xapian_path, *compact_xapian_path;
1133 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1134 notmuch_database_t *notmuch = NULL;
1135 struct stat statbuf;
1137 char *message = NULL;
1139 local = talloc_new (NULL);
1141 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1143 ret = notmuch_database_open_verbose (path,
1144 NOTMUCH_DATABASE_MODE_READ_WRITE,
1148 if (status_cb) status_cb (message, closure);
1152 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1153 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1157 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1158 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1162 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1163 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1167 if (backup_path == NULL) {
1168 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1169 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1172 keep_backup = false;
1178 if (stat (backup_path, &statbuf) != -1) {
1179 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1180 ret = NOTMUCH_STATUS_FILE_ERROR;
1183 if (errno != ENOENT) {
1184 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1186 ret = NOTMUCH_STATUS_FILE_ERROR;
1190 /* Unconditionally attempt to remove old work-in-progress database (if
1191 * any). This is "protected" by database lock. If this fails due to write
1192 * errors (etc), the following code will fail and provide error message.
1194 (void) rmtree (compact_xapian_path);
1197 NotmuchCompactor compactor (status_cb, closure);
1199 compactor.set_renumber (false);
1200 compactor.add_source (xapian_path);
1201 compactor.set_destdir (compact_xapian_path);
1202 compactor.compact ();
1203 } catch (const Xapian::Error &error) {
1204 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1205 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1209 if (rename (xapian_path, backup_path)) {
1210 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1211 xapian_path, backup_path, strerror (errno));
1212 ret = NOTMUCH_STATUS_FILE_ERROR;
1216 if (rename (compact_xapian_path, xapian_path)) {
1217 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1218 compact_xapian_path, xapian_path, strerror (errno));
1219 ret = NOTMUCH_STATUS_FILE_ERROR;
1223 if (! keep_backup) {
1224 if (rmtree (backup_path)) {
1225 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1226 backup_path, strerror (errno));
1227 ret = NOTMUCH_STATUS_FILE_ERROR;
1234 notmuch_status_t ret2;
1236 const char *str = notmuch_database_status_string (notmuch);
1237 if (status_cb && str)
1238 status_cb (str, closure);
1240 ret2 = notmuch_database_destroy (notmuch);
1242 /* don't clobber previous error status */
1243 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1247 talloc_free (local);
1253 notmuch_database_destroy (notmuch_database_t *notmuch)
1255 notmuch_status_t status;
1257 status = notmuch_database_close (notmuch);
1258 talloc_free (notmuch);
1264 notmuch_database_get_path (notmuch_database_t *notmuch)
1266 return notmuch->path;
1270 notmuch_database_get_version (notmuch_database_t *notmuch)
1272 unsigned int version;
1273 string version_string;
1277 version_string = notmuch->xapian_db->get_metadata ("version");
1278 if (version_string.empty ())
1281 str = version_string.c_str ();
1282 if (str == NULL || *str == '\0')
1285 version = strtoul (str, &end, 10);
1287 INTERNAL_ERROR ("Malformed database version: %s", str);
1293 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1295 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1296 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1297 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1300 static volatile sig_atomic_t do_progress_notify = 0;
1303 handle_sigalrm (unused (int signal))
1305 do_progress_notify = 1;
1308 /* Upgrade the current database.
1310 * After opening a database in read-write mode, the client should
1311 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1312 * if so, upgrade with this function before making any modifications.
1314 * The optional progress_notify callback can be used by the caller to
1315 * provide progress indication to the user. If non-NULL it will be
1316 * called periodically with 'count' as the number of messages upgraded
1317 * so far and 'total' the overall number of messages that will be
1321 notmuch_database_upgrade (notmuch_database_t *notmuch,
1322 void (*progress_notify) (void *closure,
1326 void *local = talloc_new (NULL);
1327 Xapian::TermIterator t, t_end;
1328 Xapian::WritableDatabase *db;
1329 struct sigaction action;
1330 struct itimerval timerval;
1331 bool timer_is_active = false;
1332 enum _notmuch_features target_features, new_features;
1333 notmuch_status_t status;
1334 notmuch_private_status_t private_status;
1335 notmuch_query_t *query = NULL;
1336 unsigned int count = 0, total = 0;
1338 status = _notmuch_database_ensure_writable (notmuch);
1342 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1344 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1345 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1347 if (! notmuch_database_needs_upgrade (notmuch))
1348 return NOTMUCH_STATUS_SUCCESS;
1350 if (progress_notify) {
1351 /* Set up our handler for SIGALRM */
1352 memset (&action, 0, sizeof (struct sigaction));
1353 action.sa_handler = handle_sigalrm;
1354 sigemptyset (&action.sa_mask);
1355 action.sa_flags = SA_RESTART;
1356 sigaction (SIGALRM, &action, NULL);
1358 /* Then start a timer to send SIGALRM once per second. */
1359 timerval.it_interval.tv_sec = 1;
1360 timerval.it_interval.tv_usec = 0;
1361 timerval.it_value.tv_sec = 1;
1362 timerval.it_value.tv_usec = 0;
1363 setitimer (ITIMER_REAL, &timerval, NULL);
1365 timer_is_active = true;
1368 /* Figure out how much total work we need to do. */
1370 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1371 NOTMUCH_FEATURE_LAST_MOD)) {
1372 query = notmuch_query_create (notmuch, "");
1375 status = notmuch_query_count_messages (query, &msg_count);
1380 notmuch_query_destroy (query);
1383 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1384 t_end = db->allterms_end ("XTIMESTAMP");
1385 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1388 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1389 /* The ghost message upgrade converts all thread_id_*
1390 * metadata values into ghost message documents. */
1391 t_end = db->metadata_keys_end ("thread_id_");
1392 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1396 /* Perform the upgrade in a transaction. */
1397 db->begin_transaction (true);
1399 /* Set the target features so we write out changes in the desired
1401 notmuch->features = target_features;
1403 /* Perform per-message upgrades. */
1405 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1406 NOTMUCH_FEATURE_LAST_MOD)) {
1407 notmuch_messages_t *messages;
1408 notmuch_message_t *message;
1411 query = notmuch_query_create (notmuch, "");
1413 status = notmuch_query_search_messages (query, &messages);
1417 notmuch_messages_valid (messages);
1418 notmuch_messages_move_to_next (messages))
1420 if (do_progress_notify) {
1421 progress_notify (closure, (double) count / total);
1422 do_progress_notify = 0;
1425 message = notmuch_messages_get (messages);
1427 /* Before version 1, each message document had its
1428 * filename in the data field. Copy that into the new
1429 * format by calling notmuch_message_add_filename.
1431 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1432 filename = _notmuch_message_talloc_copy_data (message);
1433 if (filename && *filename != '\0') {
1434 _notmuch_message_add_filename (message, filename);
1435 _notmuch_message_clear_data (message);
1437 talloc_free (filename);
1440 /* Prior to version 2, the "folder:" prefix was
1441 * probabilistic and stemmed. Change it to the current
1442 * boolean prefix. Add "path:" prefixes while at it.
1444 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1445 _notmuch_message_upgrade_folder (message);
1447 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1448 * track modification revisions. Give all messages the
1449 * next available revision; since we just started tracking
1450 * revisions for this database, that will be 1.
1452 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1453 _notmuch_message_upgrade_last_mod (message);
1455 _notmuch_message_sync (message);
1457 notmuch_message_destroy (message);
1462 notmuch_query_destroy (query);
1466 /* Perform per-directory upgrades. */
1468 /* Before version 1 we stored directory timestamps in
1469 * XTIMESTAMP documents instead of the current XDIRECTORY
1470 * documents. So copy those as well. */
1471 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1472 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1474 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1478 Xapian::PostingIterator p, p_end;
1479 std::string term = *t;
1481 p_end = notmuch->xapian_db->postlist_end (term);
1483 for (p = notmuch->xapian_db->postlist_begin (term);
1487 Xapian::Document document;
1489 notmuch_directory_t *directory;
1491 if (do_progress_notify) {
1492 progress_notify (closure, (double) count / total);
1493 do_progress_notify = 0;
1496 document = find_document_for_doc_id (notmuch, *p);
1497 mtime = Xapian::sortable_unserialise (
1498 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1500 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1501 NOTMUCH_FIND_CREATE, &status);
1502 notmuch_directory_set_mtime (directory, mtime);
1503 notmuch_directory_destroy (directory);
1505 db->delete_document (*p);
1512 /* Perform metadata upgrades. */
1514 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1515 * messages were stored as database metadata. Change these to
1518 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1519 notmuch_message_t *message;
1520 std::string message_id, thread_id;
1522 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1523 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1525 if (do_progress_notify) {
1526 progress_notify (closure, (double) count / total);
1527 do_progress_notify = 0;
1530 message_id = (*t).substr (
1531 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1532 thread_id = db->get_metadata (*t);
1534 /* Create ghost message */
1535 message = _notmuch_message_create_for_message_id (
1536 notmuch, message_id.c_str (), &private_status);
1537 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1538 /* Document already exists; ignore the stored thread ID */
1539 } else if (private_status ==
1540 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1541 private_status = _notmuch_message_initialize_ghost (
1542 message, thread_id.c_str ());
1543 if (! private_status)
1544 _notmuch_message_sync (message);
1547 if (private_status) {
1548 _notmuch_database_log (notmuch,
1549 "Upgrade failed while creating ghost messages.\n");
1550 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1554 /* Clear saved metadata thread ID */
1555 db->set_metadata (*t, "");
1561 status = NOTMUCH_STATUS_SUCCESS;
1562 db->set_metadata ("features", _print_features (local, notmuch->features));
1563 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1566 if (status == NOTMUCH_STATUS_SUCCESS)
1567 db->commit_transaction ();
1569 db->cancel_transaction ();
1571 if (timer_is_active) {
1572 /* Now stop the timer. */
1573 timerval.it_interval.tv_sec = 0;
1574 timerval.it_interval.tv_usec = 0;
1575 timerval.it_value.tv_sec = 0;
1576 timerval.it_value.tv_usec = 0;
1577 setitimer (ITIMER_REAL, &timerval, NULL);
1579 /* And disable the signal handler. */
1580 action.sa_handler = SIG_IGN;
1581 sigaction (SIGALRM, &action, NULL);
1585 notmuch_query_destroy (query);
1587 talloc_free (local);
1592 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1594 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1595 notmuch->atomic_nesting > 0)
1598 if (notmuch_database_needs_upgrade (notmuch))
1599 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1602 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1603 } catch (const Xapian::Error &error) {
1604 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1605 error.get_msg().c_str());
1606 notmuch->exception_reported = true;
1607 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1611 notmuch->atomic_nesting++;
1612 return NOTMUCH_STATUS_SUCCESS;
1616 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1618 Xapian::WritableDatabase *db;
1620 if (notmuch->atomic_nesting == 0)
1621 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1623 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1624 notmuch->atomic_nesting > 1)
1627 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1629 db->commit_transaction ();
1631 /* This is a hack for testing. Xapian never flushes on a
1632 * non-flushed commit, even if the flush threshold is 1.
1633 * However, we rely on flushing to test atomicity. */
1634 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1635 if (thresh && atoi (thresh) == 1)
1637 } catch (const Xapian::Error &error) {
1638 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1639 error.get_msg().c_str());
1640 notmuch->exception_reported = true;
1641 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1644 if (notmuch->atomic_dirty) {
1645 ++notmuch->revision;
1646 notmuch->atomic_dirty = false;
1650 notmuch->atomic_nesting--;
1651 return NOTMUCH_STATUS_SUCCESS;
1655 notmuch_database_get_revision (notmuch_database_t *notmuch,
1659 *uuid = notmuch->uuid;
1660 return notmuch->revision;
1663 /* We allow the user to use arbitrarily long paths for directories. But
1664 * we have a term-length limit. So if we exceed that, we'll use the
1665 * SHA-1 of the path for the database term.
1667 * Note: This function may return the original value of 'path'. If it
1668 * does not, then the caller is responsible to free() the returned
1672 _notmuch_database_get_directory_db_path (const char *path)
1674 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1676 if (term_len > NOTMUCH_TERM_MAX)
1677 return _notmuch_sha1_of_string (path);
1682 /* Given a path, split it into two parts: the directory part is all
1683 * components except for the last, and the basename is that last
1684 * component. Getting the return-value for either part is optional
1685 * (the caller can pass NULL).
1687 * The original 'path' can represent either a regular file or a
1688 * directory---the splitting will be carried out in the same way in
1689 * either case. Trailing slashes on 'path' will be ignored, and any
1690 * cases of multiple '/' characters appearing in series will be
1691 * treated as a single '/'.
1693 * Allocation (if any) will have 'ctx' as the talloc owner. But
1694 * pointers will be returned within the original path string whenever
1697 * Note: If 'path' is non-empty and contains no non-trailing slash,
1698 * (that is, consists of a filename with no parent directory), then
1699 * the directory returned will be an empty string. However, if 'path'
1700 * is an empty string, then both directory and basename will be
1704 _notmuch_database_split_path (void *ctx,
1706 const char **directory,
1707 const char **basename)
1711 if (path == NULL || *path == '\0') {
1716 return NOTMUCH_STATUS_SUCCESS;
1719 /* Find the last slash (not counting a trailing slash), if any. */
1721 slash = path + strlen (path) - 1;
1723 /* First, skip trailing slashes. */
1724 while (slash != path && *slash == '/')
1727 /* Then, find a slash. */
1728 while (slash != path && *slash != '/') {
1735 /* Finally, skip multiple slashes. */
1736 while (slash != path && *(slash - 1) == '/')
1739 if (slash == path) {
1741 *directory = talloc_strdup (ctx, "");
1746 *directory = talloc_strndup (ctx, path, slash - path);
1749 return NOTMUCH_STATUS_SUCCESS;
1752 /* Find the document ID of the specified directory.
1754 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1755 * created if one does not exist for 'path'. Otherwise, if the
1756 * directory document does not exist, this sets *directory_id to
1757 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1760 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1762 notmuch_find_flags_t flags,
1763 unsigned int *directory_id)
1765 notmuch_directory_t *directory;
1766 notmuch_status_t status;
1770 return NOTMUCH_STATUS_SUCCESS;
1773 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1774 if (status || !directory) {
1779 *directory_id = _notmuch_directory_get_document_id (directory);
1781 notmuch_directory_destroy (directory);
1783 return NOTMUCH_STATUS_SUCCESS;
1787 _notmuch_database_get_directory_path (void *ctx,
1788 notmuch_database_t *notmuch,
1789 unsigned int doc_id)
1791 Xapian::Document document;
1793 document = find_document_for_doc_id (notmuch, doc_id);
1795 return talloc_strdup (ctx, document.get_data ().c_str ());
1798 /* Given a legal 'filename' for the database, (either relative to
1799 * database path or absolute with initial components identical to
1800 * database path), return a new string (with 'ctx' as the talloc
1801 * owner) suitable for use as a direntry term value.
1803 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1804 * will be created in the database as needed. Otherwise, if the
1805 * necessary directory documents do not exist, this sets
1806 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1809 _notmuch_database_filename_to_direntry (void *ctx,
1810 notmuch_database_t *notmuch,
1811 const char *filename,
1812 notmuch_find_flags_t flags,
1815 const char *relative, *directory, *basename;
1816 Xapian::docid directory_id;
1817 notmuch_status_t status;
1819 relative = _notmuch_database_relative_path (notmuch, filename);
1821 status = _notmuch_database_split_path (ctx, relative,
1822 &directory, &basename);
1826 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1828 if (status || directory_id == (unsigned int)-1) {
1833 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1835 return NOTMUCH_STATUS_SUCCESS;
1838 /* Given a legal 'path' for the database, return the relative path.
1840 * The return value will be a pointer to the original path contents,
1841 * and will be either the original string (if 'path' was relative) or
1842 * a portion of the string (if path was absolute and begins with the
1846 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1849 const char *db_path, *relative;
1850 unsigned int db_path_len;
1852 db_path = notmuch_database_get_path (notmuch);
1853 db_path_len = strlen (db_path);
1857 if (*relative == '/') {
1858 while (*relative == '/' && *(relative+1) == '/')
1861 if (strncmp (relative, db_path, db_path_len) == 0)
1863 relative += db_path_len;
1864 while (*relative == '/')
1873 notmuch_database_get_directory (notmuch_database_t *notmuch,
1875 notmuch_directory_t **directory)
1877 notmuch_status_t status;
1879 if (directory == NULL)
1880 return NOTMUCH_STATUS_NULL_POINTER;
1884 *directory = _notmuch_directory_create (notmuch, path,
1885 NOTMUCH_FIND_LOOKUP, &status);
1886 } catch (const Xapian::Error &error) {
1887 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1888 error.get_msg().c_str());
1889 notmuch->exception_reported = true;
1890 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1895 /* Allocate a document ID that satisfies the following criteria:
1897 * 1. The ID does not exist for any document in the Xapian database
1899 * 2. The ID was not previously returned from this function
1901 * 3. The ID is the smallest integer satisfying (1) and (2)
1903 * This function will trigger an internal error if these constraints
1904 * cannot all be satisfied, (that is, the pool of available document
1905 * IDs has been exhausted).
1908 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1910 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1912 notmuch->last_doc_id++;
1914 if (notmuch->last_doc_id == 0)
1915 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1917 return notmuch->last_doc_id;
1921 notmuch_database_remove_message (notmuch_database_t *notmuch,
1922 const char *filename)
1924 notmuch_status_t status;
1925 notmuch_message_t *message;
1927 status = notmuch_database_find_message_by_filename (notmuch, filename,
1930 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1931 status = _notmuch_message_remove_filename (message, filename);
1932 if (status == NOTMUCH_STATUS_SUCCESS)
1933 _notmuch_message_delete (message);
1934 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1935 _notmuch_message_sync (message);
1937 notmuch_message_destroy (message);
1944 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1945 const char *filename,
1946 notmuch_message_t **message_ret)
1949 const char *prefix = _find_prefix ("file-direntry");
1950 char *direntry, *term;
1951 Xapian::PostingIterator i, end;
1952 notmuch_status_t status;
1954 if (message_ret == NULL)
1955 return NOTMUCH_STATUS_NULL_POINTER;
1957 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1958 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1960 /* return NULL on any failure */
1961 *message_ret = NULL;
1963 local = talloc_new (notmuch);
1966 status = _notmuch_database_filename_to_direntry (
1967 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1968 if (status || !direntry)
1971 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1973 find_doc_ids_for_term (notmuch, term, &i, &end);
1976 notmuch_private_status_t private_status;
1978 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1980 if (*message_ret == NULL)
1981 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1983 } catch (const Xapian::Error &error) {
1984 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1985 error.get_msg().c_str());
1986 notmuch->exception_reported = true;
1987 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1991 talloc_free (local);
1993 if (status && *message_ret) {
1994 notmuch_message_destroy (*message_ret);
1995 *message_ret = NULL;
2000 notmuch_string_list_t *
2001 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2002 Xapian::TermIterator &end,
2005 int prefix_len = strlen (prefix);
2006 notmuch_string_list_t *list;
2008 list = _notmuch_string_list_create (ctx);
2009 if (unlikely (list == NULL))
2012 for (i.skip_to (prefix); i != end; i++) {
2013 /* Terminate loop at first term without desired prefix. */
2014 if (strncmp ((*i).c_str (), prefix, prefix_len))
2017 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2024 notmuch_database_get_all_tags (notmuch_database_t *db)
2026 Xapian::TermIterator i, end;
2027 notmuch_string_list_t *tags;
2030 i = db->xapian_db->allterms_begin();
2031 end = db->xapian_db->allterms_end();
2032 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2033 _find_prefix ("tag"));
2034 _notmuch_string_list_sort (tags);
2035 return _notmuch_tags_create (db, tags);
2036 } catch (const Xapian::Error &error) {
2037 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2038 error.get_msg().c_str());
2039 db->exception_reported = true;
2045 notmuch_database_status_string (const notmuch_database_t *notmuch)
2047 return notmuch->status_string;