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";
417 case NOTMUCH_STATUS_LAST_STATUS:
418 return "Unknown error status value";
423 _notmuch_database_log (notmuch_database_t *notmuch,
429 va_start (va_args, format);
431 if (notmuch->status_string)
432 talloc_free (notmuch->status_string);
434 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
439 _notmuch_database_log_append (notmuch_database_t *notmuch,
445 va_start (va_args, format);
447 if (notmuch->status_string)
448 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
450 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
456 find_doc_ids_for_term (notmuch_database_t *notmuch,
458 Xapian::PostingIterator *begin,
459 Xapian::PostingIterator *end)
461 *begin = notmuch->xapian_db->postlist_begin (term);
463 *end = notmuch->xapian_db->postlist_end (term);
467 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
468 const char *prefix_name,
470 Xapian::PostingIterator *begin,
471 Xapian::PostingIterator *end)
475 term = talloc_asprintf (notmuch, "%s%s",
476 _find_prefix (prefix_name), value);
478 find_doc_ids_for_term (notmuch, term, begin, end);
483 notmuch_private_status_t
484 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
485 const char *prefix_name,
487 unsigned int *doc_id)
489 Xapian::PostingIterator i, end;
491 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
495 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
500 #if DEBUG_DATABASE_SANITY
504 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
508 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
511 static Xapian::Document
512 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
514 return notmuch->xapian_db->get_document (doc_id);
517 /* Generate a compressed version of 'message_id' of the form:
519 * notmuch-sha1-<sha1_sum_of_message_id>
522 _notmuch_message_id_compressed (void *ctx, const char *message_id)
524 char *sha1, *compressed;
526 sha1 = _notmuch_sha1_of_string (message_id);
528 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
535 notmuch_database_find_message (notmuch_database_t *notmuch,
536 const char *message_id,
537 notmuch_message_t **message_ret)
539 notmuch_private_status_t status;
542 if (message_ret == NULL)
543 return NOTMUCH_STATUS_NULL_POINTER;
545 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
546 message_id = _notmuch_message_id_compressed (notmuch, message_id);
549 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
550 message_id, &doc_id);
552 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
555 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
557 if (*message_ret == NULL)
558 return NOTMUCH_STATUS_OUT_OF_MEMORY;
561 return NOTMUCH_STATUS_SUCCESS;
562 } catch (const Xapian::Error &error) {
563 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
564 error.get_msg().c_str());
565 notmuch->exception_reported = TRUE;
567 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
572 notmuch_database_create (const char *path, notmuch_database_t **database)
574 char *status_string = NULL;
575 notmuch_status_t status;
577 status = notmuch_database_create_verbose (path, database,
581 fputs (status_string, stderr);
582 free (status_string);
589 notmuch_database_create_verbose (const char *path,
590 notmuch_database_t **database,
591 char **status_string)
593 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
594 notmuch_database_t *notmuch = NULL;
595 char *notmuch_path = NULL;
596 char *message = NULL;
601 message = strdup ("Error: Cannot create a database for a NULL path.\n");
602 status = NOTMUCH_STATUS_NULL_POINTER;
606 if (path[0] != '/') {
607 message = strdup ("Error: Database path must be absolute.\n");
608 status = NOTMUCH_STATUS_PATH_ERROR;
612 err = stat (path, &st);
614 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
615 path, strerror (errno)));
616 status = NOTMUCH_STATUS_FILE_ERROR;
620 if (! S_ISDIR (st.st_mode)) {
621 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
622 "Not a directory.\n",
624 status = NOTMUCH_STATUS_FILE_ERROR;
628 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
630 err = mkdir (notmuch_path, 0755);
633 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
634 notmuch_path, strerror (errno)));
635 status = NOTMUCH_STATUS_FILE_ERROR;
639 status = notmuch_database_open_verbose (path,
640 NOTMUCH_DATABASE_MODE_READ_WRITE,
645 /* Upgrade doesn't add these feature to existing databases, but
646 * new databases have them. */
647 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
648 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
650 status = notmuch_database_upgrade (notmuch, NULL, NULL);
652 notmuch_database_close(notmuch);
658 talloc_free (notmuch_path);
662 *status_string = message;
669 talloc_free (notmuch);
674 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
676 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
677 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
678 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
681 return NOTMUCH_STATUS_SUCCESS;
684 /* Allocate a revision number for the next change. */
686 _notmuch_database_new_revision (notmuch_database_t *notmuch)
688 unsigned long new_revision = notmuch->revision + 1;
690 /* If we're in an atomic section, hold off on updating the
691 * committed revision number until we commit the atomic section.
693 if (notmuch->atomic_nesting)
694 notmuch->atomic_dirty = TRUE;
696 notmuch->revision = new_revision;
701 /* Parse a database features string from the given database version.
702 * Returns the feature bit set.
704 * For version < 3, this ignores the features string and returns a
705 * hard-coded set of features.
707 * If there are unrecognized features that are required to open the
708 * database in mode (which should be 'r' or 'w'), return a
709 * comma-separated list of unrecognized but required features in
710 * *incompat_out suitable for presenting to the user. *incompat_out
711 * will be allocated from ctx.
713 static _notmuch_features
714 _parse_features (const void *ctx, const char *features, unsigned int version,
715 char mode, char **incompat_out)
717 _notmuch_features res = static_cast<_notmuch_features>(0);
718 unsigned int namelen, i;
722 /* Prior to database version 3, features were implied by the
725 return NOTMUCH_FEATURES_V0;
726 else if (version == 1)
727 return NOTMUCH_FEATURES_V1;
728 else if (version == 2)
729 return NOTMUCH_FEATURES_V2;
731 /* Parse the features string */
732 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
733 flags = strchr (features, '\t');
734 if (! flags || flags > features + llen)
736 namelen = flags - features;
738 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
739 if (strlen (feature_names[i].name) == namelen &&
740 strncmp (feature_names[i].name, features, namelen) == 0) {
741 res |= feature_names[i].value;
746 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
747 /* Unrecognized feature */
748 const char *have = strchr (flags, mode);
749 if (have && have < features + llen) {
750 /* This feature is required to access this database in
751 * 'mode', but we don't understand it. */
753 *incompat_out = talloc_strdup (ctx, "");
754 *incompat_out = talloc_asprintf_append_buffer (
755 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
765 _print_features (const void *ctx, unsigned int features)
768 char *res = talloc_strdup (ctx, "");
770 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
771 if (features & feature_names[i].value)
772 res = talloc_asprintf_append_buffer (
773 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
779 notmuch_database_open (const char *path,
780 notmuch_database_mode_t mode,
781 notmuch_database_t **database)
783 char *status_string = NULL;
784 notmuch_status_t status;
786 status = notmuch_database_open_verbose (path, mode, database,
790 fputs (status_string, stderr);
791 free (status_string);
798 notmuch_database_open_verbose (const char *path,
799 notmuch_database_mode_t mode,
800 notmuch_database_t **database,
801 char **status_string)
803 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
804 void *local = talloc_new (NULL);
805 notmuch_database_t *notmuch = NULL;
806 char *notmuch_path, *xapian_path, *incompat_features;
807 char *message = NULL;
810 unsigned int i, version;
811 static int initialized = 0;
814 message = strdup ("Error: Cannot open a database for a NULL path.\n");
815 status = NOTMUCH_STATUS_NULL_POINTER;
819 if (path[0] != '/') {
820 message = strdup ("Error: Database path must be absolute.\n");
821 status = NOTMUCH_STATUS_PATH_ERROR;
825 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
826 message = strdup ("Out of memory\n");
827 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
831 err = stat (notmuch_path, &st);
833 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
834 notmuch_path, strerror (errno)));
835 status = NOTMUCH_STATUS_FILE_ERROR;
839 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
840 message = strdup ("Out of memory\n");
841 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
845 /* Initialize the GLib type system and threads */
846 #if !GLIB_CHECK_VERSION(2, 35, 1)
850 /* Initialize gmime */
852 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
856 notmuch = talloc_zero (NULL, notmuch_database_t);
857 notmuch->exception_reported = FALSE;
858 notmuch->status_string = NULL;
859 notmuch->path = talloc_strdup (notmuch, path);
861 strip_trailing(notmuch->path, '/');
863 notmuch->mode = mode;
864 notmuch->atomic_nesting = 0;
867 string last_thread_id;
870 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
871 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
874 notmuch->xapian_db = new Xapian::Database (xapian_path);
877 /* Check version. As of database version 3, we represent
878 * changes in terms of features, so assume a version bump
879 * means a dramatically incompatible change. */
880 version = notmuch_database_get_version (notmuch);
881 if (version > NOTMUCH_DATABASE_VERSION) {
882 IGNORE_RESULT (asprintf (&message,
883 "Error: Notmuch database at %s\n"
884 " has a newer database format version (%u) than supported by this\n"
885 " version of notmuch (%u).\n",
886 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
887 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
888 notmuch_database_destroy (notmuch);
890 status = NOTMUCH_STATUS_FILE_ERROR;
894 /* Check features. */
895 incompat_features = NULL;
896 notmuch->features = _parse_features (
897 local, notmuch->xapian_db->get_metadata ("features").c_str (),
898 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
900 if (incompat_features) {
901 IGNORE_RESULT (asprintf (&message,
902 "Error: Notmuch database at %s\n"
903 " requires features (%s)\n"
904 " not supported by this version of notmuch.\n",
905 notmuch_path, incompat_features));
906 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
907 notmuch_database_destroy (notmuch);
909 status = NOTMUCH_STATUS_FILE_ERROR;
913 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
914 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
915 if (last_thread_id.empty ()) {
916 notmuch->last_thread_id = 0;
921 str = last_thread_id.c_str ();
922 notmuch->last_thread_id = strtoull (str, &end, 16);
924 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
927 /* Get current highest revision number. */
928 last_mod = notmuch->xapian_db->get_value_upper_bound (
929 NOTMUCH_VALUE_LAST_MOD);
930 if (last_mod.empty ())
931 notmuch->revision = 0;
933 notmuch->revision = Xapian::sortable_unserialise (last_mod);
934 notmuch->uuid = talloc_strdup (
935 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
937 notmuch->query_parser = new Xapian::QueryParser;
938 notmuch->term_gen = new Xapian::TermGenerator;
939 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
940 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
941 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
942 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
944 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
945 notmuch->query_parser->set_database (*notmuch->xapian_db);
946 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
947 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
948 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
949 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
950 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
952 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
953 const prefix_t *prefix = &prefix_table[i];
954 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
955 _setup_query_field (prefix, notmuch);
958 } catch (const Xapian::Error &error) {
959 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
960 error.get_msg().c_str()));
961 notmuch_database_destroy (notmuch);
963 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
971 *status_string = message;
979 talloc_free (notmuch);
984 notmuch_database_close (notmuch_database_t *notmuch)
986 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
988 /* Many Xapian objects (and thus notmuch objects) hold references to
989 * the database, so merely deleting the database may not suffice to
990 * close it. Thus, we explicitly close it here. */
991 if (notmuch->xapian_db != NULL) {
993 /* If there's an outstanding transaction, it's unclear if
994 * closing the Xapian database commits everything up to
995 * that transaction, or may discard committed (but
996 * unflushed) transactions. To be certain, explicitly
997 * cancel any outstanding transaction before closing. */
998 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
999 notmuch->atomic_nesting)
1000 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1001 ->cancel_transaction ();
1003 /* Close the database. This implicitly flushes
1004 * outstanding changes. */
1005 notmuch->xapian_db->close();
1006 } catch (const Xapian::Error &error) {
1007 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1008 if (! notmuch->exception_reported) {
1009 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1010 error.get_msg().c_str());
1015 delete notmuch->term_gen;
1016 notmuch->term_gen = NULL;
1017 delete notmuch->query_parser;
1018 notmuch->query_parser = NULL;
1019 delete notmuch->xapian_db;
1020 notmuch->xapian_db = NULL;
1021 delete notmuch->value_range_processor;
1022 notmuch->value_range_processor = NULL;
1023 delete notmuch->date_range_processor;
1024 notmuch->date_range_processor = NULL;
1025 delete notmuch->last_mod_range_processor;
1026 notmuch->last_mod_range_processor = NULL;
1032 _notmuch_database_reopen (notmuch_database_t *notmuch)
1034 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1035 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1038 notmuch->xapian_db->reopen ();
1039 } catch (const Xapian::Error &error) {
1040 if (! notmuch->exception_reported) {
1041 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1042 error.get_msg ().c_str ());
1043 notmuch->exception_reported = TRUE;
1045 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1050 return NOTMUCH_STATUS_SUCCESS;
1054 unlink_cb (const char *path,
1055 unused (const struct stat *sb),
1057 unused (struct FTW *ftw))
1059 return remove (path);
1063 rmtree (const char *path)
1065 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1068 class NotmuchCompactor : public Xapian::Compactor
1070 notmuch_compact_status_cb_t status_cb;
1071 void *status_closure;
1074 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1075 status_cb (cb), status_closure (closure) { }
1078 set_status (const std::string &table, const std::string &status)
1082 if (status_cb == NULL)
1085 if (status.length () == 0)
1086 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1088 msg = talloc_asprintf (NULL, " %s", status.c_str());
1094 status_cb (msg, status_closure);
1099 /* Compacts the given database, optionally saving the original database
1100 * in backup_path. Additionally, a callback function can be provided to
1101 * give the user feedback on the progress of the (likely long-lived)
1102 * compaction process.
1104 * The backup path must point to a directory on the same volume as the
1105 * original database. Passing a NULL backup_path will result in the
1106 * uncompacted database being deleted after compaction has finished.
1107 * Note that the database write lock will be held during the
1108 * compaction process to protect data integrity.
1111 notmuch_database_compact (const char *path,
1112 const char *backup_path,
1113 notmuch_compact_status_cb_t status_cb,
1117 char *notmuch_path, *xapian_path, *compact_xapian_path;
1118 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1119 notmuch_database_t *notmuch = NULL;
1120 struct stat statbuf;
1121 notmuch_bool_t keep_backup;
1122 char *message = NULL;
1124 local = talloc_new (NULL);
1126 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1128 ret = notmuch_database_open_verbose (path,
1129 NOTMUCH_DATABASE_MODE_READ_WRITE,
1133 if (status_cb) status_cb (message, closure);
1137 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1138 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1142 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1143 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1147 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1148 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1152 if (backup_path == NULL) {
1153 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1154 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1157 keep_backup = FALSE;
1163 if (stat (backup_path, &statbuf) != -1) {
1164 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1165 ret = NOTMUCH_STATUS_FILE_ERROR;
1168 if (errno != ENOENT) {
1169 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1171 ret = NOTMUCH_STATUS_FILE_ERROR;
1175 /* Unconditionally attempt to remove old work-in-progress database (if
1176 * any). This is "protected" by database lock. If this fails due to write
1177 * errors (etc), the following code will fail and provide error message.
1179 (void) rmtree (compact_xapian_path);
1182 NotmuchCompactor compactor (status_cb, closure);
1184 compactor.set_renumber (false);
1185 compactor.add_source (xapian_path);
1186 compactor.set_destdir (compact_xapian_path);
1187 compactor.compact ();
1188 } catch (const Xapian::Error &error) {
1189 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1190 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1194 if (rename (xapian_path, backup_path)) {
1195 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1196 xapian_path, backup_path, strerror (errno));
1197 ret = NOTMUCH_STATUS_FILE_ERROR;
1201 if (rename (compact_xapian_path, xapian_path)) {
1202 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1203 compact_xapian_path, xapian_path, strerror (errno));
1204 ret = NOTMUCH_STATUS_FILE_ERROR;
1208 if (! keep_backup) {
1209 if (rmtree (backup_path)) {
1210 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1211 backup_path, strerror (errno));
1212 ret = NOTMUCH_STATUS_FILE_ERROR;
1219 notmuch_status_t ret2;
1221 const char *str = notmuch_database_status_string (notmuch);
1222 if (status_cb && str)
1223 status_cb (str, closure);
1225 ret2 = notmuch_database_destroy (notmuch);
1227 /* don't clobber previous error status */
1228 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1232 talloc_free (local);
1238 notmuch_database_destroy (notmuch_database_t *notmuch)
1240 notmuch_status_t status;
1242 status = notmuch_database_close (notmuch);
1243 talloc_free (notmuch);
1249 notmuch_database_get_path (notmuch_database_t *notmuch)
1251 return notmuch->path;
1255 notmuch_database_get_version (notmuch_database_t *notmuch)
1257 unsigned int version;
1258 string version_string;
1262 version_string = notmuch->xapian_db->get_metadata ("version");
1263 if (version_string.empty ())
1266 str = version_string.c_str ();
1267 if (str == NULL || *str == '\0')
1270 version = strtoul (str, &end, 10);
1272 INTERNAL_ERROR ("Malformed database version: %s", str);
1278 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1280 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1281 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1282 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1285 static volatile sig_atomic_t do_progress_notify = 0;
1288 handle_sigalrm (unused (int signal))
1290 do_progress_notify = 1;
1293 /* Upgrade the current database.
1295 * After opening a database in read-write mode, the client should
1296 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1297 * if so, upgrade with this function before making any modifications.
1299 * The optional progress_notify callback can be used by the caller to
1300 * provide progress indication to the user. If non-NULL it will be
1301 * called periodically with 'count' as the number of messages upgraded
1302 * so far and 'total' the overall number of messages that will be
1306 notmuch_database_upgrade (notmuch_database_t *notmuch,
1307 void (*progress_notify) (void *closure,
1311 void *local = talloc_new (NULL);
1312 Xapian::TermIterator t, t_end;
1313 Xapian::WritableDatabase *db;
1314 struct sigaction action;
1315 struct itimerval timerval;
1316 notmuch_bool_t timer_is_active = FALSE;
1317 enum _notmuch_features target_features, new_features;
1318 notmuch_status_t status;
1319 notmuch_private_status_t private_status;
1320 notmuch_query_t *query = NULL;
1321 unsigned int count = 0, total = 0;
1323 status = _notmuch_database_ensure_writable (notmuch);
1327 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1329 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1330 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1332 if (! notmuch_database_needs_upgrade (notmuch))
1333 return NOTMUCH_STATUS_SUCCESS;
1335 if (progress_notify) {
1336 /* Set up our handler for SIGALRM */
1337 memset (&action, 0, sizeof (struct sigaction));
1338 action.sa_handler = handle_sigalrm;
1339 sigemptyset (&action.sa_mask);
1340 action.sa_flags = SA_RESTART;
1341 sigaction (SIGALRM, &action, NULL);
1343 /* Then start a timer to send SIGALRM once per second. */
1344 timerval.it_interval.tv_sec = 1;
1345 timerval.it_interval.tv_usec = 0;
1346 timerval.it_value.tv_sec = 1;
1347 timerval.it_value.tv_usec = 0;
1348 setitimer (ITIMER_REAL, &timerval, NULL);
1350 timer_is_active = TRUE;
1353 /* Figure out how much total work we need to do. */
1355 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1356 NOTMUCH_FEATURE_LAST_MOD)) {
1357 query = notmuch_query_create (notmuch, "");
1360 status = notmuch_query_count_messages (query, &msg_count);
1365 notmuch_query_destroy (query);
1368 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1369 t_end = db->allterms_end ("XTIMESTAMP");
1370 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1373 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1374 /* The ghost message upgrade converts all thread_id_*
1375 * metadata values into ghost message documents. */
1376 t_end = db->metadata_keys_end ("thread_id_");
1377 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1381 /* Perform the upgrade in a transaction. */
1382 db->begin_transaction (true);
1384 /* Set the target features so we write out changes in the desired
1386 notmuch->features = target_features;
1388 /* Perform per-message upgrades. */
1390 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1391 NOTMUCH_FEATURE_LAST_MOD)) {
1392 notmuch_messages_t *messages;
1393 notmuch_message_t *message;
1396 query = notmuch_query_create (notmuch, "");
1398 status = notmuch_query_search_messages (query, &messages);
1402 notmuch_messages_valid (messages);
1403 notmuch_messages_move_to_next (messages))
1405 if (do_progress_notify) {
1406 progress_notify (closure, (double) count / total);
1407 do_progress_notify = 0;
1410 message = notmuch_messages_get (messages);
1412 /* Before version 1, each message document had its
1413 * filename in the data field. Copy that into the new
1414 * format by calling notmuch_message_add_filename.
1416 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1417 filename = _notmuch_message_talloc_copy_data (message);
1418 if (filename && *filename != '\0') {
1419 _notmuch_message_add_filename (message, filename);
1420 _notmuch_message_clear_data (message);
1422 talloc_free (filename);
1425 /* Prior to version 2, the "folder:" prefix was
1426 * probabilistic and stemmed. Change it to the current
1427 * boolean prefix. Add "path:" prefixes while at it.
1429 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1430 _notmuch_message_upgrade_folder (message);
1432 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1433 * track modification revisions. Give all messages the
1434 * next available revision; since we just started tracking
1435 * revisions for this database, that will be 1.
1437 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1438 _notmuch_message_upgrade_last_mod (message);
1440 _notmuch_message_sync (message);
1442 notmuch_message_destroy (message);
1447 notmuch_query_destroy (query);
1451 /* Perform per-directory upgrades. */
1453 /* Before version 1 we stored directory timestamps in
1454 * XTIMESTAMP documents instead of the current XDIRECTORY
1455 * documents. So copy those as well. */
1456 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1457 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1459 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1463 Xapian::PostingIterator p, p_end;
1464 std::string term = *t;
1466 p_end = notmuch->xapian_db->postlist_end (term);
1468 for (p = notmuch->xapian_db->postlist_begin (term);
1472 Xapian::Document document;
1474 notmuch_directory_t *directory;
1476 if (do_progress_notify) {
1477 progress_notify (closure, (double) count / total);
1478 do_progress_notify = 0;
1481 document = find_document_for_doc_id (notmuch, *p);
1482 mtime = Xapian::sortable_unserialise (
1483 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1485 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1486 NOTMUCH_FIND_CREATE, &status);
1487 notmuch_directory_set_mtime (directory, mtime);
1488 notmuch_directory_destroy (directory);
1490 db->delete_document (*p);
1497 /* Perform metadata upgrades. */
1499 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1500 * messages were stored as database metadata. Change these to
1503 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1504 notmuch_message_t *message;
1505 std::string message_id, thread_id;
1507 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1508 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1510 if (do_progress_notify) {
1511 progress_notify (closure, (double) count / total);
1512 do_progress_notify = 0;
1515 message_id = (*t).substr (
1516 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1517 thread_id = db->get_metadata (*t);
1519 /* Create ghost message */
1520 message = _notmuch_message_create_for_message_id (
1521 notmuch, message_id.c_str (), &private_status);
1522 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1523 /* Document already exists; ignore the stored thread ID */
1524 } else if (private_status ==
1525 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1526 private_status = _notmuch_message_initialize_ghost (
1527 message, thread_id.c_str ());
1528 if (! private_status)
1529 _notmuch_message_sync (message);
1532 if (private_status) {
1533 _notmuch_database_log (notmuch,
1534 "Upgrade failed while creating ghost messages.\n");
1535 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1539 /* Clear saved metadata thread ID */
1540 db->set_metadata (*t, "");
1546 status = NOTMUCH_STATUS_SUCCESS;
1547 db->set_metadata ("features", _print_features (local, notmuch->features));
1548 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1551 if (status == NOTMUCH_STATUS_SUCCESS)
1552 db->commit_transaction ();
1554 db->cancel_transaction ();
1556 if (timer_is_active) {
1557 /* Now stop the timer. */
1558 timerval.it_interval.tv_sec = 0;
1559 timerval.it_interval.tv_usec = 0;
1560 timerval.it_value.tv_sec = 0;
1561 timerval.it_value.tv_usec = 0;
1562 setitimer (ITIMER_REAL, &timerval, NULL);
1564 /* And disable the signal handler. */
1565 action.sa_handler = SIG_IGN;
1566 sigaction (SIGALRM, &action, NULL);
1570 notmuch_query_destroy (query);
1572 talloc_free (local);
1577 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1579 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1580 notmuch->atomic_nesting > 0)
1583 if (notmuch_database_needs_upgrade (notmuch))
1584 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1587 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1588 } catch (const Xapian::Error &error) {
1589 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1590 error.get_msg().c_str());
1591 notmuch->exception_reported = TRUE;
1592 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1596 notmuch->atomic_nesting++;
1597 return NOTMUCH_STATUS_SUCCESS;
1601 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1603 Xapian::WritableDatabase *db;
1605 if (notmuch->atomic_nesting == 0)
1606 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1608 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1609 notmuch->atomic_nesting > 1)
1612 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1614 db->commit_transaction ();
1616 /* This is a hack for testing. Xapian never flushes on a
1617 * non-flushed commit, even if the flush threshold is 1.
1618 * However, we rely on flushing to test atomicity. */
1619 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1620 if (thresh && atoi (thresh) == 1)
1622 } catch (const Xapian::Error &error) {
1623 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1624 error.get_msg().c_str());
1625 notmuch->exception_reported = TRUE;
1626 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1629 if (notmuch->atomic_dirty) {
1630 ++notmuch->revision;
1631 notmuch->atomic_dirty = FALSE;
1635 notmuch->atomic_nesting--;
1636 return NOTMUCH_STATUS_SUCCESS;
1640 notmuch_database_get_revision (notmuch_database_t *notmuch,
1644 *uuid = notmuch->uuid;
1645 return notmuch->revision;
1648 /* We allow the user to use arbitrarily long paths for directories. But
1649 * we have a term-length limit. So if we exceed that, we'll use the
1650 * SHA-1 of the path for the database term.
1652 * Note: This function may return the original value of 'path'. If it
1653 * does not, then the caller is responsible to free() the returned
1657 _notmuch_database_get_directory_db_path (const char *path)
1659 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1661 if (term_len > NOTMUCH_TERM_MAX)
1662 return _notmuch_sha1_of_string (path);
1667 /* Given a path, split it into two parts: the directory part is all
1668 * components except for the last, and the basename is that last
1669 * component. Getting the return-value for either part is optional
1670 * (the caller can pass NULL).
1672 * The original 'path' can represent either a regular file or a
1673 * directory---the splitting will be carried out in the same way in
1674 * either case. Trailing slashes on 'path' will be ignored, and any
1675 * cases of multiple '/' characters appearing in series will be
1676 * treated as a single '/'.
1678 * Allocation (if any) will have 'ctx' as the talloc owner. But
1679 * pointers will be returned within the original path string whenever
1682 * Note: If 'path' is non-empty and contains no non-trailing slash,
1683 * (that is, consists of a filename with no parent directory), then
1684 * the directory returned will be an empty string. However, if 'path'
1685 * is an empty string, then both directory and basename will be
1689 _notmuch_database_split_path (void *ctx,
1691 const char **directory,
1692 const char **basename)
1696 if (path == NULL || *path == '\0') {
1701 return NOTMUCH_STATUS_SUCCESS;
1704 /* Find the last slash (not counting a trailing slash), if any. */
1706 slash = path + strlen (path) - 1;
1708 /* First, skip trailing slashes. */
1709 while (slash != path && *slash == '/')
1712 /* Then, find a slash. */
1713 while (slash != path && *slash != '/') {
1720 /* Finally, skip multiple slashes. */
1721 while (slash != path && *(slash - 1) == '/')
1724 if (slash == path) {
1726 *directory = talloc_strdup (ctx, "");
1731 *directory = talloc_strndup (ctx, path, slash - path);
1734 return NOTMUCH_STATUS_SUCCESS;
1737 /* Find the document ID of the specified directory.
1739 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1740 * created if one does not exist for 'path'. Otherwise, if the
1741 * directory document does not exist, this sets *directory_id to
1742 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1745 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1747 notmuch_find_flags_t flags,
1748 unsigned int *directory_id)
1750 notmuch_directory_t *directory;
1751 notmuch_status_t status;
1755 return NOTMUCH_STATUS_SUCCESS;
1758 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1759 if (status || !directory) {
1764 *directory_id = _notmuch_directory_get_document_id (directory);
1766 notmuch_directory_destroy (directory);
1768 return NOTMUCH_STATUS_SUCCESS;
1772 _notmuch_database_get_directory_path (void *ctx,
1773 notmuch_database_t *notmuch,
1774 unsigned int doc_id)
1776 Xapian::Document document;
1778 document = find_document_for_doc_id (notmuch, doc_id);
1780 return talloc_strdup (ctx, document.get_data ().c_str ());
1783 /* Given a legal 'filename' for the database, (either relative to
1784 * database path or absolute with initial components identical to
1785 * database path), return a new string (with 'ctx' as the talloc
1786 * owner) suitable for use as a direntry term value.
1788 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1789 * will be created in the database as needed. Otherwise, if the
1790 * necessary directory documents do not exist, this sets
1791 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1794 _notmuch_database_filename_to_direntry (void *ctx,
1795 notmuch_database_t *notmuch,
1796 const char *filename,
1797 notmuch_find_flags_t flags,
1800 const char *relative, *directory, *basename;
1801 Xapian::docid directory_id;
1802 notmuch_status_t status;
1804 relative = _notmuch_database_relative_path (notmuch, filename);
1806 status = _notmuch_database_split_path (ctx, relative,
1807 &directory, &basename);
1811 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1813 if (status || directory_id == (unsigned int)-1) {
1818 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1820 return NOTMUCH_STATUS_SUCCESS;
1823 /* Given a legal 'path' for the database, return the relative path.
1825 * The return value will be a pointer to the original path contents,
1826 * and will be either the original string (if 'path' was relative) or
1827 * a portion of the string (if path was absolute and begins with the
1831 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1834 const char *db_path, *relative;
1835 unsigned int db_path_len;
1837 db_path = notmuch_database_get_path (notmuch);
1838 db_path_len = strlen (db_path);
1842 if (*relative == '/') {
1843 while (*relative == '/' && *(relative+1) == '/')
1846 if (strncmp (relative, db_path, db_path_len) == 0)
1848 relative += db_path_len;
1849 while (*relative == '/')
1858 notmuch_database_get_directory (notmuch_database_t *notmuch,
1860 notmuch_directory_t **directory)
1862 notmuch_status_t status;
1864 if (directory == NULL)
1865 return NOTMUCH_STATUS_NULL_POINTER;
1869 *directory = _notmuch_directory_create (notmuch, path,
1870 NOTMUCH_FIND_LOOKUP, &status);
1871 } catch (const Xapian::Error &error) {
1872 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1873 error.get_msg().c_str());
1874 notmuch->exception_reported = TRUE;
1875 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1880 /* Allocate a document ID that satisfies the following criteria:
1882 * 1. The ID does not exist for any document in the Xapian database
1884 * 2. The ID was not previously returned from this function
1886 * 3. The ID is the smallest integer satisfying (1) and (2)
1888 * This function will trigger an internal error if these constraints
1889 * cannot all be satisfied, (that is, the pool of available document
1890 * IDs has been exhausted).
1893 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1895 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1897 notmuch->last_doc_id++;
1899 if (notmuch->last_doc_id == 0)
1900 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1902 return notmuch->last_doc_id;
1906 notmuch_database_remove_message (notmuch_database_t *notmuch,
1907 const char *filename)
1909 notmuch_status_t status;
1910 notmuch_message_t *message;
1912 status = notmuch_database_find_message_by_filename (notmuch, filename,
1915 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1916 status = _notmuch_message_remove_filename (message, filename);
1917 if (status == NOTMUCH_STATUS_SUCCESS)
1918 _notmuch_message_delete (message);
1919 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1920 _notmuch_message_sync (message);
1922 notmuch_message_destroy (message);
1929 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1930 const char *filename,
1931 notmuch_message_t **message_ret)
1934 const char *prefix = _find_prefix ("file-direntry");
1935 char *direntry, *term;
1936 Xapian::PostingIterator i, end;
1937 notmuch_status_t status;
1939 if (message_ret == NULL)
1940 return NOTMUCH_STATUS_NULL_POINTER;
1942 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1943 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1945 /* return NULL on any failure */
1946 *message_ret = NULL;
1948 local = talloc_new (notmuch);
1951 status = _notmuch_database_filename_to_direntry (
1952 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1953 if (status || !direntry)
1956 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1958 find_doc_ids_for_term (notmuch, term, &i, &end);
1961 notmuch_private_status_t private_status;
1963 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1965 if (*message_ret == NULL)
1966 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1968 } catch (const Xapian::Error &error) {
1969 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1970 error.get_msg().c_str());
1971 notmuch->exception_reported = TRUE;
1972 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1976 talloc_free (local);
1978 if (status && *message_ret) {
1979 notmuch_message_destroy (*message_ret);
1980 *message_ret = NULL;
1985 notmuch_string_list_t *
1986 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1987 Xapian::TermIterator &end,
1990 int prefix_len = strlen (prefix);
1991 notmuch_string_list_t *list;
1993 list = _notmuch_string_list_create (ctx);
1994 if (unlikely (list == NULL))
1997 for (i.skip_to (prefix); i != end; i++) {
1998 /* Terminate loop at first term without desired prefix. */
1999 if (strncmp ((*i).c_str (), prefix, prefix_len))
2002 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2009 notmuch_database_get_all_tags (notmuch_database_t *db)
2011 Xapian::TermIterator i, end;
2012 notmuch_string_list_t *tags;
2015 i = db->xapian_db->allterms_begin();
2016 end = db->xapian_db->allterms_end();
2017 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2018 _find_prefix ("tag"));
2019 _notmuch_string_list_sort (tags);
2020 return _notmuch_tags_create (db, tags);
2021 } catch (const Xapian::Error &error) {
2022 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2023 error.get_msg().c_str());
2024 db->exception_reported = TRUE;
2030 notmuch_database_status_string (const notmuch_database_t *notmuch)
2032 return notmuch->status_string;