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 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
862 notmuch->path[strlen (notmuch->path) - 1] = '\0';
864 notmuch->mode = mode;
865 notmuch->atomic_nesting = 0;
868 string last_thread_id;
871 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
872 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
875 notmuch->xapian_db = new Xapian::Database (xapian_path);
878 /* Check version. As of database version 3, we represent
879 * changes in terms of features, so assume a version bump
880 * means a dramatically incompatible change. */
881 version = notmuch_database_get_version (notmuch);
882 if (version > NOTMUCH_DATABASE_VERSION) {
883 IGNORE_RESULT (asprintf (&message,
884 "Error: Notmuch database at %s\n"
885 " has a newer database format version (%u) than supported by this\n"
886 " version of notmuch (%u).\n",
887 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
888 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
889 notmuch_database_destroy (notmuch);
891 status = NOTMUCH_STATUS_FILE_ERROR;
895 /* Check features. */
896 incompat_features = NULL;
897 notmuch->features = _parse_features (
898 local, notmuch->xapian_db->get_metadata ("features").c_str (),
899 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
901 if (incompat_features) {
902 IGNORE_RESULT (asprintf (&message,
903 "Error: Notmuch database at %s\n"
904 " requires features (%s)\n"
905 " not supported by this version of notmuch.\n",
906 notmuch_path, incompat_features));
907 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
908 notmuch_database_destroy (notmuch);
910 status = NOTMUCH_STATUS_FILE_ERROR;
914 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
915 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
916 if (last_thread_id.empty ()) {
917 notmuch->last_thread_id = 0;
922 str = last_thread_id.c_str ();
923 notmuch->last_thread_id = strtoull (str, &end, 16);
925 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
928 /* Get current highest revision number. */
929 last_mod = notmuch->xapian_db->get_value_upper_bound (
930 NOTMUCH_VALUE_LAST_MOD);
931 if (last_mod.empty ())
932 notmuch->revision = 0;
934 notmuch->revision = Xapian::sortable_unserialise (last_mod);
935 notmuch->uuid = talloc_strdup (
936 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
938 notmuch->query_parser = new Xapian::QueryParser;
939 notmuch->term_gen = new Xapian::TermGenerator;
940 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
941 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
942 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
943 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
945 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
946 notmuch->query_parser->set_database (*notmuch->xapian_db);
947 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
948 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
949 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
950 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
951 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
953 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
954 const prefix_t *prefix = &prefix_table[i];
955 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
956 _setup_query_field (prefix, notmuch);
959 } catch (const Xapian::Error &error) {
960 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
961 error.get_msg().c_str()));
962 notmuch_database_destroy (notmuch);
964 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
972 *status_string = message;
980 talloc_free (notmuch);
985 notmuch_database_close (notmuch_database_t *notmuch)
987 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
989 /* Many Xapian objects (and thus notmuch objects) hold references to
990 * the database, so merely deleting the database may not suffice to
991 * close it. Thus, we explicitly close it here. */
992 if (notmuch->xapian_db != NULL) {
994 /* If there's an outstanding transaction, it's unclear if
995 * closing the Xapian database commits everything up to
996 * that transaction, or may discard committed (but
997 * unflushed) transactions. To be certain, explicitly
998 * cancel any outstanding transaction before closing. */
999 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1000 notmuch->atomic_nesting)
1001 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1002 ->cancel_transaction ();
1004 /* Close the database. This implicitly flushes
1005 * outstanding changes. */
1006 notmuch->xapian_db->close();
1007 } catch (const Xapian::Error &error) {
1008 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1009 if (! notmuch->exception_reported) {
1010 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1011 error.get_msg().c_str());
1016 delete notmuch->term_gen;
1017 notmuch->term_gen = NULL;
1018 delete notmuch->query_parser;
1019 notmuch->query_parser = NULL;
1020 delete notmuch->xapian_db;
1021 notmuch->xapian_db = NULL;
1022 delete notmuch->value_range_processor;
1023 notmuch->value_range_processor = NULL;
1024 delete notmuch->date_range_processor;
1025 notmuch->date_range_processor = NULL;
1026 delete notmuch->last_mod_range_processor;
1027 notmuch->last_mod_range_processor = NULL;
1033 _notmuch_database_reopen (notmuch_database_t *notmuch)
1035 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1036 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1039 notmuch->xapian_db->reopen ();
1040 } catch (const Xapian::Error &error) {
1041 if (! notmuch->exception_reported) {
1042 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1043 error.get_msg ().c_str ());
1044 notmuch->exception_reported = TRUE;
1046 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1051 return NOTMUCH_STATUS_SUCCESS;
1055 unlink_cb (const char *path,
1056 unused (const struct stat *sb),
1058 unused (struct FTW *ftw))
1060 return remove (path);
1064 rmtree (const char *path)
1066 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1069 class NotmuchCompactor : public Xapian::Compactor
1071 notmuch_compact_status_cb_t status_cb;
1072 void *status_closure;
1075 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1076 status_cb (cb), status_closure (closure) { }
1079 set_status (const std::string &table, const std::string &status)
1083 if (status_cb == NULL)
1086 if (status.length () == 0)
1087 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1089 msg = talloc_asprintf (NULL, " %s", status.c_str());
1095 status_cb (msg, status_closure);
1100 /* Compacts the given database, optionally saving the original database
1101 * in backup_path. Additionally, a callback function can be provided to
1102 * give the user feedback on the progress of the (likely long-lived)
1103 * compaction process.
1105 * The backup path must point to a directory on the same volume as the
1106 * original database. Passing a NULL backup_path will result in the
1107 * uncompacted database being deleted after compaction has finished.
1108 * Note that the database write lock will be held during the
1109 * compaction process to protect data integrity.
1112 notmuch_database_compact (const char *path,
1113 const char *backup_path,
1114 notmuch_compact_status_cb_t status_cb,
1118 char *notmuch_path, *xapian_path, *compact_xapian_path;
1119 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1120 notmuch_database_t *notmuch = NULL;
1121 struct stat statbuf;
1122 notmuch_bool_t keep_backup;
1123 char *message = NULL;
1125 local = talloc_new (NULL);
1127 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1129 ret = notmuch_database_open_verbose (path,
1130 NOTMUCH_DATABASE_MODE_READ_WRITE,
1134 if (status_cb) status_cb (message, closure);
1138 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1139 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1143 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1144 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1148 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1149 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1153 if (backup_path == NULL) {
1154 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1155 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1158 keep_backup = FALSE;
1164 if (stat (backup_path, &statbuf) != -1) {
1165 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1166 ret = NOTMUCH_STATUS_FILE_ERROR;
1169 if (errno != ENOENT) {
1170 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1172 ret = NOTMUCH_STATUS_FILE_ERROR;
1176 /* Unconditionally attempt to remove old work-in-progress database (if
1177 * any). This is "protected" by database lock. If this fails due to write
1178 * errors (etc), the following code will fail and provide error message.
1180 (void) rmtree (compact_xapian_path);
1183 NotmuchCompactor compactor (status_cb, closure);
1185 compactor.set_renumber (false);
1186 compactor.add_source (xapian_path);
1187 compactor.set_destdir (compact_xapian_path);
1188 compactor.compact ();
1189 } catch (const Xapian::Error &error) {
1190 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1191 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1195 if (rename (xapian_path, backup_path)) {
1196 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1197 xapian_path, backup_path, strerror (errno));
1198 ret = NOTMUCH_STATUS_FILE_ERROR;
1202 if (rename (compact_xapian_path, xapian_path)) {
1203 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1204 compact_xapian_path, xapian_path, strerror (errno));
1205 ret = NOTMUCH_STATUS_FILE_ERROR;
1209 if (! keep_backup) {
1210 if (rmtree (backup_path)) {
1211 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1212 backup_path, strerror (errno));
1213 ret = NOTMUCH_STATUS_FILE_ERROR;
1220 notmuch_status_t ret2;
1222 const char *str = notmuch_database_status_string (notmuch);
1223 if (status_cb && str)
1224 status_cb (str, closure);
1226 ret2 = notmuch_database_destroy (notmuch);
1228 /* don't clobber previous error status */
1229 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1233 talloc_free (local);
1239 notmuch_database_destroy (notmuch_database_t *notmuch)
1241 notmuch_status_t status;
1243 status = notmuch_database_close (notmuch);
1244 talloc_free (notmuch);
1250 notmuch_database_get_path (notmuch_database_t *notmuch)
1252 return notmuch->path;
1256 notmuch_database_get_version (notmuch_database_t *notmuch)
1258 unsigned int version;
1259 string version_string;
1263 version_string = notmuch->xapian_db->get_metadata ("version");
1264 if (version_string.empty ())
1267 str = version_string.c_str ();
1268 if (str == NULL || *str == '\0')
1271 version = strtoul (str, &end, 10);
1273 INTERNAL_ERROR ("Malformed database version: %s", str);
1279 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1281 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1282 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1283 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1286 static volatile sig_atomic_t do_progress_notify = 0;
1289 handle_sigalrm (unused (int signal))
1291 do_progress_notify = 1;
1294 /* Upgrade the current database.
1296 * After opening a database in read-write mode, the client should
1297 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1298 * if so, upgrade with this function before making any modifications.
1300 * The optional progress_notify callback can be used by the caller to
1301 * provide progress indication to the user. If non-NULL it will be
1302 * called periodically with 'count' as the number of messages upgraded
1303 * so far and 'total' the overall number of messages that will be
1307 notmuch_database_upgrade (notmuch_database_t *notmuch,
1308 void (*progress_notify) (void *closure,
1312 void *local = talloc_new (NULL);
1313 Xapian::TermIterator t, t_end;
1314 Xapian::WritableDatabase *db;
1315 struct sigaction action;
1316 struct itimerval timerval;
1317 notmuch_bool_t timer_is_active = FALSE;
1318 enum _notmuch_features target_features, new_features;
1319 notmuch_status_t status;
1320 notmuch_private_status_t private_status;
1321 notmuch_query_t *query = NULL;
1322 unsigned int count = 0, total = 0;
1324 status = _notmuch_database_ensure_writable (notmuch);
1328 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1330 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1331 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1333 if (! notmuch_database_needs_upgrade (notmuch))
1334 return NOTMUCH_STATUS_SUCCESS;
1336 if (progress_notify) {
1337 /* Set up our handler for SIGALRM */
1338 memset (&action, 0, sizeof (struct sigaction));
1339 action.sa_handler = handle_sigalrm;
1340 sigemptyset (&action.sa_mask);
1341 action.sa_flags = SA_RESTART;
1342 sigaction (SIGALRM, &action, NULL);
1344 /* Then start a timer to send SIGALRM once per second. */
1345 timerval.it_interval.tv_sec = 1;
1346 timerval.it_interval.tv_usec = 0;
1347 timerval.it_value.tv_sec = 1;
1348 timerval.it_value.tv_usec = 0;
1349 setitimer (ITIMER_REAL, &timerval, NULL);
1351 timer_is_active = TRUE;
1354 /* Figure out how much total work we need to do. */
1356 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1357 NOTMUCH_FEATURE_LAST_MOD)) {
1358 query = notmuch_query_create (notmuch, "");
1361 status = notmuch_query_count_messages (query, &msg_count);
1366 notmuch_query_destroy (query);
1369 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1370 t_end = db->allterms_end ("XTIMESTAMP");
1371 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1374 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1375 /* The ghost message upgrade converts all thread_id_*
1376 * metadata values into ghost message documents. */
1377 t_end = db->metadata_keys_end ("thread_id_");
1378 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1382 /* Perform the upgrade in a transaction. */
1383 db->begin_transaction (true);
1385 /* Set the target features so we write out changes in the desired
1387 notmuch->features = target_features;
1389 /* Perform per-message upgrades. */
1391 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1392 NOTMUCH_FEATURE_LAST_MOD)) {
1393 notmuch_messages_t *messages;
1394 notmuch_message_t *message;
1397 query = notmuch_query_create (notmuch, "");
1399 status = notmuch_query_search_messages (query, &messages);
1403 notmuch_messages_valid (messages);
1404 notmuch_messages_move_to_next (messages))
1406 if (do_progress_notify) {
1407 progress_notify (closure, (double) count / total);
1408 do_progress_notify = 0;
1411 message = notmuch_messages_get (messages);
1413 /* Before version 1, each message document had its
1414 * filename in the data field. Copy that into the new
1415 * format by calling notmuch_message_add_filename.
1417 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1418 filename = _notmuch_message_talloc_copy_data (message);
1419 if (filename && *filename != '\0') {
1420 _notmuch_message_add_filename (message, filename);
1421 _notmuch_message_clear_data (message);
1423 talloc_free (filename);
1426 /* Prior to version 2, the "folder:" prefix was
1427 * probabilistic and stemmed. Change it to the current
1428 * boolean prefix. Add "path:" prefixes while at it.
1430 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1431 _notmuch_message_upgrade_folder (message);
1433 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1434 * track modification revisions. Give all messages the
1435 * next available revision; since we just started tracking
1436 * revisions for this database, that will be 1.
1438 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1439 _notmuch_message_upgrade_last_mod (message);
1441 _notmuch_message_sync (message);
1443 notmuch_message_destroy (message);
1448 notmuch_query_destroy (query);
1452 /* Perform per-directory upgrades. */
1454 /* Before version 1 we stored directory timestamps in
1455 * XTIMESTAMP documents instead of the current XDIRECTORY
1456 * documents. So copy those as well. */
1457 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1458 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1460 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1464 Xapian::PostingIterator p, p_end;
1465 std::string term = *t;
1467 p_end = notmuch->xapian_db->postlist_end (term);
1469 for (p = notmuch->xapian_db->postlist_begin (term);
1473 Xapian::Document document;
1475 notmuch_directory_t *directory;
1477 if (do_progress_notify) {
1478 progress_notify (closure, (double) count / total);
1479 do_progress_notify = 0;
1482 document = find_document_for_doc_id (notmuch, *p);
1483 mtime = Xapian::sortable_unserialise (
1484 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1486 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1487 NOTMUCH_FIND_CREATE, &status);
1488 notmuch_directory_set_mtime (directory, mtime);
1489 notmuch_directory_destroy (directory);
1491 db->delete_document (*p);
1498 /* Perform metadata upgrades. */
1500 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1501 * messages were stored as database metadata. Change these to
1504 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1505 notmuch_message_t *message;
1506 std::string message_id, thread_id;
1508 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1509 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1511 if (do_progress_notify) {
1512 progress_notify (closure, (double) count / total);
1513 do_progress_notify = 0;
1516 message_id = (*t).substr (
1517 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1518 thread_id = db->get_metadata (*t);
1520 /* Create ghost message */
1521 message = _notmuch_message_create_for_message_id (
1522 notmuch, message_id.c_str (), &private_status);
1523 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1524 /* Document already exists; ignore the stored thread ID */
1525 } else if (private_status ==
1526 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1527 private_status = _notmuch_message_initialize_ghost (
1528 message, thread_id.c_str ());
1529 if (! private_status)
1530 _notmuch_message_sync (message);
1533 if (private_status) {
1534 _notmuch_database_log (notmuch,
1535 "Upgrade failed while creating ghost messages.\n");
1536 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1540 /* Clear saved metadata thread ID */
1541 db->set_metadata (*t, "");
1547 status = NOTMUCH_STATUS_SUCCESS;
1548 db->set_metadata ("features", _print_features (local, notmuch->features));
1549 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1552 if (status == NOTMUCH_STATUS_SUCCESS)
1553 db->commit_transaction ();
1555 db->cancel_transaction ();
1557 if (timer_is_active) {
1558 /* Now stop the timer. */
1559 timerval.it_interval.tv_sec = 0;
1560 timerval.it_interval.tv_usec = 0;
1561 timerval.it_value.tv_sec = 0;
1562 timerval.it_value.tv_usec = 0;
1563 setitimer (ITIMER_REAL, &timerval, NULL);
1565 /* And disable the signal handler. */
1566 action.sa_handler = SIG_IGN;
1567 sigaction (SIGALRM, &action, NULL);
1571 notmuch_query_destroy (query);
1573 talloc_free (local);
1578 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1580 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1581 notmuch->atomic_nesting > 0)
1584 if (notmuch_database_needs_upgrade (notmuch))
1585 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1588 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1589 } catch (const Xapian::Error &error) {
1590 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1591 error.get_msg().c_str());
1592 notmuch->exception_reported = TRUE;
1593 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1597 notmuch->atomic_nesting++;
1598 return NOTMUCH_STATUS_SUCCESS;
1602 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1604 Xapian::WritableDatabase *db;
1606 if (notmuch->atomic_nesting == 0)
1607 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1609 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1610 notmuch->atomic_nesting > 1)
1613 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1615 db->commit_transaction ();
1617 /* This is a hack for testing. Xapian never flushes on a
1618 * non-flushed commit, even if the flush threshold is 1.
1619 * However, we rely on flushing to test atomicity. */
1620 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1621 if (thresh && atoi (thresh) == 1)
1623 } catch (const Xapian::Error &error) {
1624 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1625 error.get_msg().c_str());
1626 notmuch->exception_reported = TRUE;
1627 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1630 if (notmuch->atomic_dirty) {
1631 ++notmuch->revision;
1632 notmuch->atomic_dirty = FALSE;
1636 notmuch->atomic_nesting--;
1637 return NOTMUCH_STATUS_SUCCESS;
1641 notmuch_database_get_revision (notmuch_database_t *notmuch,
1645 *uuid = notmuch->uuid;
1646 return notmuch->revision;
1649 /* We allow the user to use arbitrarily long paths for directories. But
1650 * we have a term-length limit. So if we exceed that, we'll use the
1651 * SHA-1 of the path for the database term.
1653 * Note: This function may return the original value of 'path'. If it
1654 * does not, then the caller is responsible to free() the returned
1658 _notmuch_database_get_directory_db_path (const char *path)
1660 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1662 if (term_len > NOTMUCH_TERM_MAX)
1663 return _notmuch_sha1_of_string (path);
1668 /* Given a path, split it into two parts: the directory part is all
1669 * components except for the last, and the basename is that last
1670 * component. Getting the return-value for either part is optional
1671 * (the caller can pass NULL).
1673 * The original 'path' can represent either a regular file or a
1674 * directory---the splitting will be carried out in the same way in
1675 * either case. Trailing slashes on 'path' will be ignored, and any
1676 * cases of multiple '/' characters appearing in series will be
1677 * treated as a single '/'.
1679 * Allocation (if any) will have 'ctx' as the talloc owner. But
1680 * pointers will be returned within the original path string whenever
1683 * Note: If 'path' is non-empty and contains no non-trailing slash,
1684 * (that is, consists of a filename with no parent directory), then
1685 * the directory returned will be an empty string. However, if 'path'
1686 * is an empty string, then both directory and basename will be
1690 _notmuch_database_split_path (void *ctx,
1692 const char **directory,
1693 const char **basename)
1697 if (path == NULL || *path == '\0') {
1702 return NOTMUCH_STATUS_SUCCESS;
1705 /* Find the last slash (not counting a trailing slash), if any. */
1707 slash = path + strlen (path) - 1;
1709 /* First, skip trailing slashes. */
1710 while (slash != path && *slash == '/')
1713 /* Then, find a slash. */
1714 while (slash != path && *slash != '/') {
1721 /* Finally, skip multiple slashes. */
1722 while (slash != path && *(slash - 1) == '/')
1725 if (slash == path) {
1727 *directory = talloc_strdup (ctx, "");
1732 *directory = talloc_strndup (ctx, path, slash - path);
1735 return NOTMUCH_STATUS_SUCCESS;
1738 /* Find the document ID of the specified directory.
1740 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1741 * created if one does not exist for 'path'. Otherwise, if the
1742 * directory document does not exist, this sets *directory_id to
1743 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1746 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1748 notmuch_find_flags_t flags,
1749 unsigned int *directory_id)
1751 notmuch_directory_t *directory;
1752 notmuch_status_t status;
1756 return NOTMUCH_STATUS_SUCCESS;
1759 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1760 if (status || !directory) {
1765 *directory_id = _notmuch_directory_get_document_id (directory);
1767 notmuch_directory_destroy (directory);
1769 return NOTMUCH_STATUS_SUCCESS;
1773 _notmuch_database_get_directory_path (void *ctx,
1774 notmuch_database_t *notmuch,
1775 unsigned int doc_id)
1777 Xapian::Document document;
1779 document = find_document_for_doc_id (notmuch, doc_id);
1781 return talloc_strdup (ctx, document.get_data ().c_str ());
1784 /* Given a legal 'filename' for the database, (either relative to
1785 * database path or absolute with initial components identical to
1786 * database path), return a new string (with 'ctx' as the talloc
1787 * owner) suitable for use as a direntry term value.
1789 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1790 * will be created in the database as needed. Otherwise, if the
1791 * necessary directory documents do not exist, this sets
1792 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1795 _notmuch_database_filename_to_direntry (void *ctx,
1796 notmuch_database_t *notmuch,
1797 const char *filename,
1798 notmuch_find_flags_t flags,
1801 const char *relative, *directory, *basename;
1802 Xapian::docid directory_id;
1803 notmuch_status_t status;
1805 relative = _notmuch_database_relative_path (notmuch, filename);
1807 status = _notmuch_database_split_path (ctx, relative,
1808 &directory, &basename);
1812 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1814 if (status || directory_id == (unsigned int)-1) {
1819 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1821 return NOTMUCH_STATUS_SUCCESS;
1824 /* Given a legal 'path' for the database, return the relative path.
1826 * The return value will be a pointer to the original path contents,
1827 * and will be either the original string (if 'path' was relative) or
1828 * a portion of the string (if path was absolute and begins with the
1832 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1835 const char *db_path, *relative;
1836 unsigned int db_path_len;
1838 db_path = notmuch_database_get_path (notmuch);
1839 db_path_len = strlen (db_path);
1843 if (*relative == '/') {
1844 while (*relative == '/' && *(relative+1) == '/')
1847 if (strncmp (relative, db_path, db_path_len) == 0)
1849 relative += db_path_len;
1850 while (*relative == '/')
1859 notmuch_database_get_directory (notmuch_database_t *notmuch,
1861 notmuch_directory_t **directory)
1863 notmuch_status_t status;
1865 if (directory == NULL)
1866 return NOTMUCH_STATUS_NULL_POINTER;
1870 *directory = _notmuch_directory_create (notmuch, path,
1871 NOTMUCH_FIND_LOOKUP, &status);
1872 } catch (const Xapian::Error &error) {
1873 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1874 error.get_msg().c_str());
1875 notmuch->exception_reported = TRUE;
1876 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1881 /* Allocate a document ID that satisfies the following criteria:
1883 * 1. The ID does not exist for any document in the Xapian database
1885 * 2. The ID was not previously returned from this function
1887 * 3. The ID is the smallest integer satisfying (1) and (2)
1889 * This function will trigger an internal error if these constraints
1890 * cannot all be satisfied, (that is, the pool of available document
1891 * IDs has been exhausted).
1894 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1896 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1898 notmuch->last_doc_id++;
1900 if (notmuch->last_doc_id == 0)
1901 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1903 return notmuch->last_doc_id;
1907 notmuch_database_remove_message (notmuch_database_t *notmuch,
1908 const char *filename)
1910 notmuch_status_t status;
1911 notmuch_message_t *message;
1913 status = notmuch_database_find_message_by_filename (notmuch, filename,
1916 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1917 status = _notmuch_message_remove_filename (message, filename);
1918 if (status == NOTMUCH_STATUS_SUCCESS)
1919 _notmuch_message_delete (message);
1920 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1921 _notmuch_message_sync (message);
1923 notmuch_message_destroy (message);
1930 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1931 const char *filename,
1932 notmuch_message_t **message_ret)
1935 const char *prefix = _find_prefix ("file-direntry");
1936 char *direntry, *term;
1937 Xapian::PostingIterator i, end;
1938 notmuch_status_t status;
1940 if (message_ret == NULL)
1941 return NOTMUCH_STATUS_NULL_POINTER;
1943 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1944 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1946 /* return NULL on any failure */
1947 *message_ret = NULL;
1949 local = talloc_new (notmuch);
1952 status = _notmuch_database_filename_to_direntry (
1953 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1954 if (status || !direntry)
1957 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1959 find_doc_ids_for_term (notmuch, term, &i, &end);
1962 notmuch_private_status_t private_status;
1964 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1966 if (*message_ret == NULL)
1967 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1969 } catch (const Xapian::Error &error) {
1970 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1971 error.get_msg().c_str());
1972 notmuch->exception_reported = TRUE;
1973 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1977 talloc_free (local);
1979 if (status && *message_ret) {
1980 notmuch_message_destroy (*message_ret);
1981 *message_ret = NULL;
1986 notmuch_string_list_t *
1987 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1988 Xapian::TermIterator &end,
1991 int prefix_len = strlen (prefix);
1992 notmuch_string_list_t *list;
1994 list = _notmuch_string_list_create (ctx);
1995 if (unlikely (list == NULL))
1998 for (i.skip_to (prefix); i != end; i++) {
1999 /* Terminate loop at first term without desired prefix. */
2000 if (strncmp ((*i).c_str (), prefix, prefix_len))
2003 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2010 notmuch_database_get_all_tags (notmuch_database_t *db)
2012 Xapian::TermIterator i, end;
2013 notmuch_string_list_t *tags;
2016 i = db->xapian_db->allterms_begin();
2017 end = db->xapian_db->allterms_end();
2018 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2019 _find_prefix ("tag"));
2020 _notmuch_string_list_sort (tags);
2021 return _notmuch_tags_create (db, tags);
2022 } catch (const Xapian::Error &error) {
2023 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2024 error.get_msg().c_str());
2025 db->exception_reported = TRUE;
2031 notmuch_database_status_string (const notmuch_database_t *notmuch)
2033 return notmuch->status_string;