]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib/compact: replace deprecated notmuch_database_open_verbose
[notmuch] / lib / database.cc
1 /* database.cc - The database interfaces of the notmuch mail library
2  *
3  * Copyright © 2009 Carl Worth
4  *
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.
9  *
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.
14  *
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/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "database-private.h"
22 #include "string-util.h"
23
24 #include <iostream>
25
26 #include <sys/time.h>
27 #include <sys/stat.h>
28 #include <signal.h>
29 #include <ftw.h>
30
31 #include <glib.h>               /* g_free, GPtrArray, GHashTable */
32 #include <glib-object.h>        /* g_type_init */
33
34 #include <gmime/gmime.h>        /* g_mime_init */
35
36 using namespace std;
37
38 typedef struct {
39     const char *name;
40     const char *prefix;
41     notmuch_field_flag_t flags;
42 } prefix_t;
43
44 #define NOTMUCH_DATABASE_VERSION 3
45
46 #define STRINGIFY(s) _SUB_STRINGIFY (s)
47 #define _SUB_STRINGIFY(s) #s
48
49 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
50
51 static void
52 _log_xapian_exception (const char *where, notmuch_database_t *notmuch,  const Xapian::Error error)
53 {
54     _notmuch_database_log (notmuch,
55                            "A Xapian exception occurred at %s: %s\n",
56                            where,
57                            error.get_msg ().c_str ());
58     notmuch->exception_reported = true;
59 }
60
61 notmuch_database_mode_t
62 _notmuch_database_mode (notmuch_database_t *notmuch)
63 {
64     if (notmuch->writable_xapian_db)
65         return NOTMUCH_DATABASE_MODE_READ_WRITE;
66     else
67         return NOTMUCH_DATABASE_MODE_READ_ONLY;
68 }
69
70 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
71  *
72  * We currently have three different types of documents (mail, ghost,
73  * and directory) and also some metadata.
74  *
75  * There are two kinds of prefixes used in notmuch. There are the
76  * human friendly 'prefix names' like "thread:", which are also used
77  * in the query parser, and the actual prefix terms in the database
78  * (e.g. "G"). The correspondence is maintained in the file scope data
79  * structure 'prefix_table'.
80  *
81  * Mail document
82  * -------------
83  * A mail document is associated with a particular email message. It
84  * is stored in one or more files on disk and is uniquely identified
85  * by its "id" field (which is generally the message ID). It is
86  * indexed with the following prefixed terms which the database uses
87  * to construct threads, etc.:
88  *
89  *    Single terms of given prefix:
90  *
91  *      type:   mail
92  *
93  *      id:     Unique ID of mail. This is from the Message-ID header
94  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
95  *              If it's present and too long, then we use
96  *              "notmuch-sha1-<sha1_sum_of_message_id>".
97  *              If this header is not present, we use
98  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
99  *
100  *      thread: The ID of the thread to which the mail belongs
101  *
102  *      replyto: The ID from the In-Reply-To header of the mail (if any).
103  *
104  *    Multiple terms of given prefix:
105  *
106  *      reference: All message IDs from In-Reply-To and References
107  *                 headers in the message.
108  *
109  *      tag:       Any tags associated with this message by the user.
110  *
111  *      file-direntry:  A colon-separated pair of values
112  *                      (INTEGER:STRING), where INTEGER is the
113  *                      document ID of a directory document, and
114  *                      STRING is the name of a file within that
115  *                      directory for this mail message.
116  *
117  *      property:       Has a property with key=value
118  *                 FIXME: if no = is present, should match on any value
119  *
120  *    A mail document also has four values:
121  *
122  *      TIMESTAMP:      The time_t value corresponding to the message's
123  *                      Date header.
124  *
125  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
126  *
127  *      FROM:           The value of the "From" header
128  *
129  *      SUBJECT:        The value of the "Subject" header
130  *
131  *      LAST_MOD:       The revision number as of the last tag or
132  *                      filename change.
133  *
134  * The prefixed terms described above are also searchable without an
135  * explicit field name, but as of notmuch 0.29 this is due to
136  * query-parser setup, not extra terms in the database.  In addition,
137  * terms from the content of the message are added without a prefix
138  * for use by the user in searching. Note that the prefix name "body"
139  * is used to refer to the empty prefix string in the database.
140  *
141  * The path of the containing folder is added with the "folder" prefix
142  * (see _notmuch_message_add_folder_terms).  Sub-paths of the the path
143  * of the mail message are added with the "path" prefix.
144  *
145  * The data portion of a mail document is empty.
146  *
147  * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
148  * -----------------------------------------------
149  * A ghost mail document is like a mail document, but where we don't
150  * have the message content.  These are used to track thread reference
151  * information for messages we haven't received.
152  *
153  * A ghost mail document has type: ghost; id and thread fields that
154  * are identical to the mail document fields; and a MESSAGE_ID value.
155  *
156  * Directory document
157  * ------------------
158  * A directory document is used by a client of the notmuch library to
159  * maintain data necessary to allow for efficient polling of mail
160  * directories.
161  *
162  * All directory documents contain one term:
163  *
164  *      directory:      The directory path (relative to the database path)
165  *                      Or the SHA1 sum of the directory path (if the
166  *                      path itself is too long to fit in a Xapian
167  *                      term).
168  *
169  * And all directory documents for directories other than top-level
170  * directories also contain the following term:
171  *
172  *      directory-direntry: A colon-separated pair of values
173  *                          (INTEGER:STRING), where INTEGER is the
174  *                          document ID of the parent directory
175  *                          document, and STRING is the name of this
176  *                          directory within that parent.
177  *
178  * All directory documents have a single value:
179  *
180  *      TIMESTAMP:      The mtime of the directory (at last scan)
181  *
182  * The data portion of a directory document contains the path of the
183  * directory (relative to the database path).
184  *
185  * Database metadata
186  * -----------------
187  * Xapian allows us to store arbitrary name-value pairs as
188  * "metadata". We currently use the following metadata names with the
189  * given meanings:
190  *
191  *      version         The database schema version, (which is distinct
192  *                      from both the notmuch package version (see
193  *                      notmuch --version) and the libnotmuch library
194  *                      version. The version is stored as an base-10
195  *                      ASCII integer. The initial database version
196  *                      was 1, (though a schema existed before that
197  *                      were no "version" database value existed at
198  *                      all). Successive versions are allocated as
199  *                      changes are made to the database (such as by
200  *                      indexing new fields).
201  *
202  *      features        The set of features supported by this
203  *                      database. This consists of a set of
204  *                      '\n'-separated lines, where each is a feature
205  *                      name, a '\t', and compatibility flags.  If the
206  *                      compatibility flags contain 'w', then the
207  *                      opener must support this feature to safely
208  *                      write this database.  If the compatibility
209  *                      flags contain 'r', then the opener must
210  *                      support this feature to read this database.
211  *                      Introduced in database version 3.
212  *
213  *      last_thread_id  The last thread ID generated. This is stored
214  *                      as a 16-byte hexadecimal ASCII representation
215  *                      of a 64-bit unsigned integer. The first ID
216  *                      generated is 1 and the value will be
217  *                      incremented for each thread ID.
218  *
219  *      C*              metadata keys starting with C indicate
220  *                      configuration data. It can be managed with the
221  *                      n_database_*config* API.  There is a convention
222  *                      of hierarchical keys separated by '.' (e.g.
223  *                      query.notmuch stores the value for the named
224  *                      query 'notmuch'), but it is not enforced by the
225  *                      API.
226  *
227  * Obsolete metadata
228  * -----------------
229  *
230  * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
231  * Instead, the database has the following additional database
232  * metadata:
233  *
234  *      thread_id_*     A pre-allocated thread ID for a particular
235  *                      message. This is actually an arbitrarily large
236  *                      family of metadata name. Any particular name is
237  *                      formed by concatenating "thread_id_" with a message
238  *                      ID (or the SHA1 sum of a message ID if it is very
239  *                      long---see description of 'id' in the mail
240  *                      document). The value stored is a thread ID.
241  *
242  *                      These thread ID metadata values are stored
243  *                      whenever a message references a parent message
244  *                      that does not yet exist in the database. A
245  *                      thread ID will be allocated and stored, and if
246  *                      the message is later added, the stored thread
247  *                      ID will be used (and the metadata value will
248  *                      be cleared).
249  *
250  *                      Even before a message is added, it's
251  *                      pre-allocated thread ID is useful so that all
252  *                      descendant messages that reference this common
253  *                      parent can be recognized as belonging to the
254  *                      same thread.
255  */
256
257
258 notmuch_string_map_iterator_t *
259 _notmuch_database_user_headers (notmuch_database_t *notmuch)
260 {
261     return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
262 }
263
264 const char *
265 notmuch_status_to_string (notmuch_status_t status)
266 {
267     switch (status) {
268     case NOTMUCH_STATUS_SUCCESS:
269         return "No error occurred";
270     case NOTMUCH_STATUS_OUT_OF_MEMORY:
271         return "Out of memory";
272     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
273         return "Attempt to write to a read-only database";
274     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
275         return "A Xapian exception occurred";
276     case NOTMUCH_STATUS_FILE_ERROR:
277         return "Something went wrong trying to read or write a file";
278     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
279         return "File is not an email";
280     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
281         return "Message ID is identical to a message in database";
282     case NOTMUCH_STATUS_NULL_POINTER:
283         return "Erroneous NULL pointer";
284     case NOTMUCH_STATUS_TAG_TOO_LONG:
285         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
286     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
287         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
288     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
289         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
290     case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
291         return "Unsupported operation";
292     case NOTMUCH_STATUS_UPGRADE_REQUIRED:
293         return "Operation requires a database upgrade";
294     case NOTMUCH_STATUS_PATH_ERROR:
295         return "Path supplied is illegal for this function";
296     case NOTMUCH_STATUS_IGNORED:
297         return "Argument was ignored";
298     case NOTMUCH_STATUS_ILLEGAL_ARGUMENT:
299         return "Illegal argument for function";
300     case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
301         return "Crypto protocol missing, malformed, or unintelligible";
302     case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
303         return "Crypto engine initialization failure";
304     case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
305         return "Unknown crypto protocol";
306     case NOTMUCH_STATUS_NO_CONFIG:
307         return "No configuration file found";
308     case NOTMUCH_STATUS_NO_DATABASE:
309         return "No database found";
310     case NOTMUCH_STATUS_DATABASE_EXISTS:
311         return "Database exists, not recreated";
312     case NOTMUCH_STATUS_BAD_QUERY_SYNTAX:
313         return "Syntax error in query";
314     default:
315     case NOTMUCH_STATUS_LAST_STATUS:
316         return "Unknown error status value";
317     }
318 }
319
320 void
321 _notmuch_database_log (notmuch_database_t *notmuch,
322                        const char *format,
323                        ...)
324 {
325     va_list va_args;
326
327     va_start (va_args, format);
328
329     if (notmuch->status_string)
330         talloc_free (notmuch->status_string);
331
332     notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
333     va_end (va_args);
334 }
335
336 void
337 _notmuch_database_log_append (notmuch_database_t *notmuch,
338                               const char *format,
339                               ...)
340 {
341     va_list va_args;
342
343     va_start (va_args, format);
344
345     if (notmuch->status_string)
346         notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
347     else
348         notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
349
350     va_end (va_args);
351 }
352
353 static void
354 find_doc_ids_for_term (notmuch_database_t *notmuch,
355                        const char *term,
356                        Xapian::PostingIterator *begin,
357                        Xapian::PostingIterator *end)
358 {
359     *begin = notmuch->xapian_db->postlist_begin (term);
360
361     *end = notmuch->xapian_db->postlist_end (term);
362 }
363
364 void
365 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
366                                 const char *prefix_name,
367                                 const char *value,
368                                 Xapian::PostingIterator *begin,
369                                 Xapian::PostingIterator *end)
370 {
371     char *term;
372
373     term = talloc_asprintf (notmuch, "%s%s",
374                             _find_prefix (prefix_name), value);
375
376     find_doc_ids_for_term (notmuch, term, begin, end);
377
378     talloc_free (term);
379 }
380
381 notmuch_private_status_t
382 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
383                                       const char *prefix_name,
384                                       const char *value,
385                                       unsigned int *doc_id)
386 {
387     Xapian::PostingIterator i, end;
388
389     _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
390
391     if (i == end) {
392         *doc_id = 0;
393         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
394     }
395
396     *doc_id = *i;
397
398 #if DEBUG_DATABASE_SANITY
399     i++;
400
401     if (i != end)
402         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
403                         prefix_name, value);
404 #endif
405
406     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
407 }
408
409 static Xapian::Document
410 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
411 {
412     return notmuch->xapian_db->get_document (doc_id);
413 }
414
415 /* Generate a compressed version of 'message_id' of the form:
416  *
417  *      notmuch-sha1-<sha1_sum_of_message_id>
418  */
419 char *
420 _notmuch_message_id_compressed (void *ctx, const char *message_id)
421 {
422     char *sha1, *compressed;
423
424     sha1 = _notmuch_sha1_of_string (message_id);
425
426     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
427     free (sha1);
428
429     return compressed;
430 }
431
432 notmuch_status_t
433 notmuch_database_find_message (notmuch_database_t *notmuch,
434                                const char *message_id,
435                                notmuch_message_t **message_ret)
436 {
437     notmuch_private_status_t status;
438     unsigned int doc_id;
439
440     if (message_ret == NULL)
441         return NOTMUCH_STATUS_NULL_POINTER;
442
443     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
444         message_id = _notmuch_message_id_compressed (notmuch, message_id);
445
446     try {
447         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
448                                                        message_id, &doc_id);
449
450         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
451             *message_ret = NULL;
452         else {
453             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
454                                                     NULL);
455             if (*message_ret == NULL)
456                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
457         }
458
459         return NOTMUCH_STATUS_SUCCESS;
460     } catch (const Xapian::Error &error) {
461         _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
462                                error.get_msg ().c_str ());
463         notmuch->exception_reported = true;
464         *message_ret = NULL;
465         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
466     }
467 }
468
469 notmuch_status_t
470 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
471 {
472     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY) {
473         _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
474         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
475     }
476
477     return NOTMUCH_STATUS_SUCCESS;
478 }
479
480 /* Allocate a revision number for the next change. */
481 unsigned long
482 _notmuch_database_new_revision (notmuch_database_t *notmuch)
483 {
484     unsigned long new_revision = notmuch->revision + 1;
485
486     /* If we're in an atomic section, hold off on updating the
487      * committed revision number until we commit the atomic section.
488      */
489     if (notmuch->atomic_nesting)
490         notmuch->atomic_dirty = true;
491     else
492         notmuch->revision = new_revision;
493
494     return new_revision;
495 }
496
497 notmuch_status_t
498 notmuch_database_close (notmuch_database_t *notmuch)
499 {
500     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
501
502     /* Many Xapian objects (and thus notmuch objects) hold references to
503      * the database, so merely deleting the database may not suffice to
504      * close it.  Thus, we explicitly close it here. */
505     if (notmuch->open) {
506         try {
507             /* Close the database.  This implicitly flushes
508              * outstanding changes. If there is an open (non-flushed)
509              * transaction, ALL pending changes will be discarded */
510             notmuch->xapian_db->close ();
511         } catch (const Xapian::Error &error) {
512             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
513             if (! notmuch->exception_reported) {
514                 _notmuch_database_log (notmuch,
515                                        "Error: A Xapian exception occurred closing database: %s\n",
516                                        error.get_msg ().c_str ());
517             }
518         }
519     }
520     notmuch->open = false;
521     return status;
522 }
523
524 static int
525 unlink_cb (const char *path,
526            unused (const struct stat *sb),
527            unused (int type),
528            unused (struct FTW *ftw))
529 {
530     return remove (path);
531 }
532
533 static int
534 rmtree (const char *path)
535 {
536     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
537 }
538
539 class NotmuchCompactor : public Xapian::Compactor
540 {
541     notmuch_compact_status_cb_t status_cb;
542     void *status_closure;
543
544 public:
545     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
546         status_cb (cb), status_closure (closure)
547     {
548     }
549
550     virtual void
551     set_status (const std::string &table, const std::string &status)
552     {
553         char *msg;
554
555         if (status_cb == NULL)
556             return;
557
558         if (status.length () == 0)
559             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
560         else
561             msg = talloc_asprintf (NULL, "     %s", status.c_str ());
562
563         if (msg == NULL) {
564             return;
565         }
566
567         status_cb (msg, status_closure);
568         talloc_free (msg);
569     }
570 };
571
572 /* Compacts the given database, optionally saving the original database
573  * in backup_path. Additionally, a callback function can be provided to
574  * give the user feedback on the progress of the (likely long-lived)
575  * compaction process.
576  *
577  * The backup path must point to a directory on the same volume as the
578  * original database. Passing a NULL backup_path will result in the
579  * uncompacted database being deleted after compaction has finished.
580  * Note that the database write lock will be held during the
581  * compaction process to protect data integrity.
582  */
583 notmuch_status_t
584 notmuch_database_compact (const char *path,
585                           const char *backup_path,
586                           notmuch_compact_status_cb_t status_cb,
587                           void *closure)
588 {
589     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
590     notmuch_database_t *notmuch = NULL;
591     char *message = NULL;
592
593     ret = notmuch_database_open_with_config (path,
594                                              NOTMUCH_DATABASE_MODE_READ_WRITE,
595                                              "",
596                                              NULL,
597                                              &notmuch,
598                                              &message);
599     if (ret) {
600         if (status_cb) status_cb (message, closure);
601         return ret;
602     }
603
604     _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
605
606     return notmuch_database_compact_db (notmuch,
607                                         backup_path,
608                                         status_cb,
609                                         closure);
610 }
611
612 notmuch_status_t
613 notmuch_database_compact_db (notmuch_database_t *notmuch,
614                              const char *backup_path,
615                              notmuch_compact_status_cb_t status_cb,
616                              void *closure)
617 {
618     void *local;
619     const char *xapian_path, *compact_xapian_path;
620     const char *path;
621     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
622     struct stat statbuf;
623     bool keep_backup;
624     char *message;
625
626     ret = _notmuch_database_ensure_writable (notmuch);
627     if (ret)
628         return ret;
629
630     path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
631     if (! path)
632         return NOTMUCH_STATUS_PATH_ERROR;
633
634     local = talloc_new (NULL);
635     if (! local)
636         return NOTMUCH_STATUS_OUT_OF_MEMORY;
637
638     ret = _notmuch_choose_xapian_path (local, path, &xapian_path, &message);
639     if (ret)
640         goto DONE;
641
642     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
643         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
644         goto DONE;
645     }
646
647     if (backup_path == NULL) {
648         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
649             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
650             goto DONE;
651         }
652         keep_backup = false;
653     } else {
654         keep_backup = true;
655     }
656
657     if (stat (backup_path, &statbuf) != -1) {
658         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
659         ret = NOTMUCH_STATUS_FILE_ERROR;
660         goto DONE;
661     }
662     if (errno != ENOENT) {
663         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
664                                strerror (errno));
665         ret = NOTMUCH_STATUS_FILE_ERROR;
666         goto DONE;
667     }
668
669     /* Unconditionally attempt to remove old work-in-progress database (if
670      * any). This is "protected" by database lock. If this fails due to write
671      * errors (etc), the following code will fail and provide error message.
672      */
673     (void) rmtree (compact_xapian_path);
674
675     try {
676         NotmuchCompactor compactor (status_cb, closure);
677         notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0,
678                                      compactor);
679     } catch (const Xapian::Error &error) {
680         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
681         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
682         goto DONE;
683     }
684
685     if (rename (xapian_path, backup_path)) {
686         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
687                                xapian_path, backup_path, strerror (errno));
688         ret = NOTMUCH_STATUS_FILE_ERROR;
689         goto DONE;
690     }
691
692     if (rename (compact_xapian_path, xapian_path)) {
693         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
694                                compact_xapian_path, xapian_path, strerror (errno));
695         ret = NOTMUCH_STATUS_FILE_ERROR;
696         goto DONE;
697     }
698
699     if (! keep_backup) {
700         if (rmtree (backup_path)) {
701             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
702                                    backup_path, strerror (errno));
703             ret = NOTMUCH_STATUS_FILE_ERROR;
704             goto DONE;
705         }
706     }
707
708   DONE:
709     if (notmuch) {
710         notmuch_status_t ret2;
711
712         const char *str = notmuch_database_status_string (notmuch);
713         if (status_cb && str)
714             status_cb (str, closure);
715
716         ret2 = notmuch_database_destroy (notmuch);
717
718         /* don't clobber previous error status */
719         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
720             ret = ret2;
721     }
722
723     talloc_free (local);
724
725     return ret;
726 }
727
728 notmuch_status_t
729 notmuch_database_destroy (notmuch_database_t *notmuch)
730 {
731     notmuch_status_t status;
732     const char *talloc_report;
733
734     talloc_report = getenv ("NOTMUCH_TALLOC_REPORT");
735     if (talloc_report && strcmp (talloc_report, "") != 0) {
736         FILE *report = fopen (talloc_report, "a");
737         if (report) {
738             talloc_report_full (notmuch, report);
739         }
740     }
741
742     status = notmuch_database_close (notmuch);
743
744     delete notmuch->term_gen;
745     notmuch->term_gen = NULL;
746     delete notmuch->query_parser;
747     notmuch->query_parser = NULL;
748     delete notmuch->xapian_db;
749     notmuch->xapian_db = NULL;
750     delete notmuch->value_range_processor;
751     notmuch->value_range_processor = NULL;
752     delete notmuch->date_range_processor;
753     notmuch->date_range_processor = NULL;
754     delete notmuch->last_mod_range_processor;
755     notmuch->last_mod_range_processor = NULL;
756
757     talloc_free (notmuch);
758
759     return status;
760 }
761
762 const char *
763 notmuch_database_get_path (notmuch_database_t *notmuch)
764 {
765     return notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
766 }
767
768 unsigned int
769 notmuch_database_get_version (notmuch_database_t *notmuch)
770 {
771     unsigned int version;
772     string version_string;
773     const char *str;
774     char *end;
775
776     try {
777         version_string = notmuch->xapian_db->get_metadata ("version");
778     } catch (const Xapian::Error &error) {
779         LOG_XAPIAN_EXCEPTION (notmuch, error);
780         return 0;
781     }
782
783     if (version_string.empty ())
784         return 0;
785
786     str = version_string.c_str ();
787     if (str == NULL || *str == '\0')
788         return 0;
789
790     version = strtoul (str, &end, 10);
791     if (*end != '\0')
792         INTERNAL_ERROR ("Malformed database version: %s", str);
793
794     return version;
795 }
796
797 notmuch_bool_t
798 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
799 {
800     unsigned int version;
801
802     if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_WRITE)
803         return FALSE;
804
805     if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
806         return TRUE;
807
808     version = notmuch_database_get_version (notmuch);
809
810     return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
811 }
812
813 static volatile sig_atomic_t do_progress_notify = 0;
814
815 static void
816 handle_sigalrm (unused (int signal))
817 {
818     do_progress_notify = 1;
819 }
820
821 /* Upgrade the current database.
822  *
823  * After opening a database in read-write mode, the client should
824  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
825  * if so, upgrade with this function before making any modifications.
826  *
827  * The optional progress_notify callback can be used by the caller to
828  * provide progress indication to the user. If non-NULL it will be
829  * called periodically with 'count' as the number of messages upgraded
830  * so far and 'total' the overall number of messages that will be
831  * converted.
832  */
833 notmuch_status_t
834 notmuch_database_upgrade (notmuch_database_t *notmuch,
835                           void (*progress_notify)(void *closure,
836                                                   double progress),
837                           void *closure)
838 {
839     void *local = talloc_new (NULL);
840     Xapian::TermIterator t, t_end;
841     Xapian::WritableDatabase *db;
842     struct sigaction action;
843     struct itimerval timerval;
844     bool timer_is_active = false;
845     enum _notmuch_features target_features, new_features;
846     notmuch_status_t status;
847     notmuch_private_status_t private_status;
848     notmuch_query_t *query = NULL;
849     unsigned int count = 0, total = 0;
850
851     status = _notmuch_database_ensure_writable (notmuch);
852     if (status)
853         return status;
854
855     db = notmuch->writable_xapian_db;
856
857     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
858     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
859
860     if (! notmuch_database_needs_upgrade (notmuch))
861         return NOTMUCH_STATUS_SUCCESS;
862
863     if (progress_notify) {
864         /* Set up our handler for SIGALRM */
865         memset (&action, 0, sizeof (struct sigaction));
866         action.sa_handler = handle_sigalrm;
867         sigemptyset (&action.sa_mask);
868         action.sa_flags = SA_RESTART;
869         sigaction (SIGALRM, &action, NULL);
870
871         /* Then start a timer to send SIGALRM once per second. */
872         timerval.it_interval.tv_sec = 1;
873         timerval.it_interval.tv_usec = 0;
874         timerval.it_value.tv_sec = 1;
875         timerval.it_value.tv_usec = 0;
876         setitimer (ITIMER_REAL, &timerval, NULL);
877
878         timer_is_active = true;
879     }
880
881     /* Figure out how much total work we need to do. */
882     if (new_features &
883         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
884          NOTMUCH_FEATURE_LAST_MOD)) {
885         query = notmuch_query_create (notmuch, "");
886         unsigned msg_count;
887
888         status = notmuch_query_count_messages (query, &msg_count);
889         if (status)
890             goto DONE;
891
892         total += msg_count;
893         notmuch_query_destroy (query);
894         query = NULL;
895     }
896     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
897         t_end = db->allterms_end ("XTIMESTAMP");
898         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
899             ++total;
900     }
901     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
902         /* The ghost message upgrade converts all thread_id_*
903          * metadata values into ghost message documents. */
904         t_end = db->metadata_keys_end ("thread_id_");
905         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
906             ++total;
907     }
908
909     /* Perform the upgrade in a transaction. */
910     db->begin_transaction (true);
911
912     /* Set the target features so we write out changes in the desired
913      * format. */
914     notmuch->features = target_features;
915
916     /* Perform per-message upgrades. */
917     if (new_features &
918         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
919          NOTMUCH_FEATURE_LAST_MOD)) {
920         notmuch_messages_t *messages;
921         notmuch_message_t *message;
922         char *filename;
923
924         query = notmuch_query_create (notmuch, "");
925
926         status = notmuch_query_search_messages (query, &messages);
927         if (status)
928             goto DONE;
929         for (;
930              notmuch_messages_valid (messages);
931              notmuch_messages_move_to_next (messages)) {
932             if (do_progress_notify) {
933                 progress_notify (closure, (double) count / total);
934                 do_progress_notify = 0;
935             }
936
937             message = notmuch_messages_get (messages);
938
939             /* Before version 1, each message document had its
940              * filename in the data field. Copy that into the new
941              * format by calling notmuch_message_add_filename.
942              */
943             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
944                 filename = _notmuch_message_talloc_copy_data (message);
945                 if (filename && *filename != '\0') {
946                     _notmuch_message_add_filename (message, filename);
947                     _notmuch_message_clear_data (message);
948                 }
949                 talloc_free (filename);
950             }
951
952             /* Prior to version 2, the "folder:" prefix was
953              * probabilistic and stemmed. Change it to the current
954              * boolean prefix. Add "path:" prefixes while at it.
955              */
956             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
957                 _notmuch_message_upgrade_folder (message);
958
959             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
960              * track modification revisions.  Give all messages the
961              * next available revision; since we just started tracking
962              * revisions for this database, that will be 1.
963              */
964             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
965                 _notmuch_message_upgrade_last_mod (message);
966
967             _notmuch_message_sync (message);
968
969             notmuch_message_destroy (message);
970
971             count++;
972         }
973
974         notmuch_query_destroy (query);
975         query = NULL;
976     }
977
978     /* Perform per-directory upgrades. */
979
980     /* Before version 1 we stored directory timestamps in
981      * XTIMESTAMP documents instead of the current XDIRECTORY
982      * documents. So copy those as well. */
983     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
984         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
985
986         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
987              t != t_end;
988              t++) {
989             Xapian::PostingIterator p, p_end;
990             std::string term = *t;
991
992             p_end = notmuch->xapian_db->postlist_end (term);
993
994             for (p = notmuch->xapian_db->postlist_begin (term);
995                  p != p_end;
996                  p++) {
997                 Xapian::Document document;
998                 time_t mtime;
999                 notmuch_directory_t *directory;
1000
1001                 if (do_progress_notify) {
1002                     progress_notify (closure, (double) count / total);
1003                     do_progress_notify = 0;
1004                 }
1005
1006                 document = find_document_for_doc_id (notmuch, *p);
1007                 mtime = Xapian::sortable_unserialise (
1008                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1009
1010                 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1011                                                                NOTMUCH_FIND_CREATE, &status);
1012                 notmuch_directory_set_mtime (directory, mtime);
1013                 notmuch_directory_destroy (directory);
1014
1015                 db->delete_document (*p);
1016             }
1017
1018             ++count;
1019         }
1020     }
1021
1022     /* Perform metadata upgrades. */
1023
1024     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1025      * messages were stored as database metadata. Change these to
1026      * ghost messages.
1027      */
1028     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1029         notmuch_message_t *message;
1030         std::string message_id, thread_id;
1031
1032         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1033         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1034              t != t_end; ++t) {
1035             if (do_progress_notify) {
1036                 progress_notify (closure, (double) count / total);
1037                 do_progress_notify = 0;
1038             }
1039
1040             message_id = (*t).substr (
1041                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1042             thread_id = db->get_metadata (*t);
1043
1044             /* Create ghost message */
1045             message = _notmuch_message_create_for_message_id (
1046                 notmuch, message_id.c_str (), &private_status);
1047             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1048                 /* Document already exists; ignore the stored thread ID */
1049             } else if (private_status ==
1050                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1051                 private_status = _notmuch_message_initialize_ghost (
1052                     message, thread_id.c_str ());
1053                 if (! private_status)
1054                     _notmuch_message_sync (message);
1055             }
1056
1057             if (private_status) {
1058                 _notmuch_database_log (notmuch,
1059                                        "Upgrade failed while creating ghost messages.\n");
1060                 status = COERCE_STATUS (private_status,
1061                                         "Unexpected status from _notmuch_message_initialize_ghost");
1062                 goto DONE;
1063             }
1064
1065             /* Clear saved metadata thread ID */
1066             db->set_metadata (*t, "");
1067
1068             ++count;
1069         }
1070     }
1071
1072     status = NOTMUCH_STATUS_SUCCESS;
1073     db->set_metadata ("features", _notmuch_database_print_features (local, notmuch->features));
1074     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1075
1076   DONE:
1077     if (status == NOTMUCH_STATUS_SUCCESS)
1078         db->commit_transaction ();
1079     else
1080         db->cancel_transaction ();
1081
1082     if (timer_is_active) {
1083         /* Now stop the timer. */
1084         timerval.it_interval.tv_sec = 0;
1085         timerval.it_interval.tv_usec = 0;
1086         timerval.it_value.tv_sec = 0;
1087         timerval.it_value.tv_usec = 0;
1088         setitimer (ITIMER_REAL, &timerval, NULL);
1089
1090         /* And disable the signal handler. */
1091         action.sa_handler = SIG_IGN;
1092         sigaction (SIGALRM, &action, NULL);
1093     }
1094
1095     if (query)
1096         notmuch_query_destroy (query);
1097
1098     talloc_free (local);
1099     return status;
1100 }
1101
1102 notmuch_status_t
1103 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1104 {
1105     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1106         notmuch->atomic_nesting > 0)
1107         goto DONE;
1108
1109     if (notmuch_database_needs_upgrade (notmuch))
1110         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1111
1112     try {
1113         notmuch->writable_xapian_db->begin_transaction (false);
1114     } catch (const Xapian::Error &error) {
1115         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1116                                error.get_msg ().c_str ());
1117         notmuch->exception_reported = true;
1118         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1119     }
1120
1121   DONE:
1122     notmuch->atomic_nesting++;
1123     return NOTMUCH_STATUS_SUCCESS;
1124 }
1125
1126 notmuch_status_t
1127 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1128 {
1129     Xapian::WritableDatabase *db;
1130
1131     if (notmuch->atomic_nesting == 0)
1132         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1133
1134     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1135         notmuch->atomic_nesting > 1)
1136         goto DONE;
1137
1138     db = notmuch->writable_xapian_db;
1139     try {
1140         db->commit_transaction ();
1141         notmuch->transaction_count++;
1142
1143         /* Xapian never flushes on a non-flushed commit, even if the
1144          * flush threshold is 1.  However, we rely on flushing to test
1145          * atomicity. On the other hand, we can't straight replace
1146          * XAPIAN_FLUSH_THRESHOLD with our autocommit counter, because
1147          * the former also applies outside notmuch atomic
1148          * commits. Hence the follow complicated  test */
1149         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1150         if ((notmuch->transaction_threshold > 0 &&
1151              notmuch->transaction_count >= notmuch->transaction_threshold) ||
1152             (thresh && atoi (thresh) == 1)) {
1153             db->commit ();
1154             notmuch->transaction_count = 0;
1155         }
1156     } catch (const Xapian::Error &error) {
1157         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1158                                error.get_msg ().c_str ());
1159         notmuch->exception_reported = true;
1160         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1161     }
1162
1163     if (notmuch->atomic_dirty) {
1164         ++notmuch->revision;
1165         notmuch->atomic_dirty = false;
1166     }
1167
1168   DONE:
1169     notmuch->atomic_nesting--;
1170     return NOTMUCH_STATUS_SUCCESS;
1171 }
1172
1173 unsigned long
1174 notmuch_database_get_revision (notmuch_database_t *notmuch,
1175                                const char **uuid)
1176 {
1177     if (uuid)
1178         *uuid = notmuch->uuid;
1179     return notmuch->revision;
1180 }
1181
1182 /* We allow the user to use arbitrarily long paths for directories. But
1183  * we have a term-length limit. So if we exceed that, we'll use the
1184  * SHA-1 of the path for the database term.
1185  *
1186  * Note: This function may return the original value of 'path'. If it
1187  * does not, then the caller is responsible to free() the returned
1188  * value.
1189  */
1190 const char *
1191 _notmuch_database_get_directory_db_path (const char *path)
1192 {
1193     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1194
1195     if (term_len > NOTMUCH_TERM_MAX)
1196         return _notmuch_sha1_of_string (path);
1197     else
1198         return path;
1199 }
1200
1201 /* Given a path, split it into two parts: the directory part is all
1202  * components except for the last, and the basename is that last
1203  * component. Getting the return-value for either part is optional
1204  * (the caller can pass NULL).
1205  *
1206  * The original 'path' can represent either a regular file or a
1207  * directory---the splitting will be carried out in the same way in
1208  * either case. Trailing slashes on 'path' will be ignored, and any
1209  * cases of multiple '/' characters appearing in series will be
1210  * treated as a single '/'.
1211  *
1212  * Allocation (if any) will have 'ctx' as the talloc owner. But
1213  * pointers will be returned within the original path string whenever
1214  * possible.
1215  *
1216  * Note: If 'path' is non-empty and contains no non-trailing slash,
1217  * (that is, consists of a filename with no parent directory), then
1218  * the directory returned will be an empty string. However, if 'path'
1219  * is an empty string, then both directory and basename will be
1220  * returned as NULL.
1221  */
1222 notmuch_status_t
1223 _notmuch_database_split_path (void *ctx,
1224                               const char *path,
1225                               const char **directory,
1226                               const char **basename)
1227 {
1228     const char *slash;
1229
1230     if (path == NULL || *path == '\0') {
1231         if (directory)
1232             *directory = NULL;
1233         if (basename)
1234             *basename = NULL;
1235         return NOTMUCH_STATUS_SUCCESS;
1236     }
1237
1238     /* Find the last slash (not counting a trailing slash), if any. */
1239
1240     slash = path + strlen (path) - 1;
1241
1242     /* First, skip trailing slashes. */
1243     while (slash != path && *slash == '/')
1244         --slash;
1245
1246     /* Then, find a slash. */
1247     while (slash != path && *slash != '/') {
1248         if (basename)
1249             *basename = slash;
1250
1251         --slash;
1252     }
1253
1254     /* Finally, skip multiple slashes. */
1255     while (slash != path && *(slash - 1) == '/')
1256         --slash;
1257
1258     if (slash == path) {
1259         if (directory)
1260             *directory = talloc_strdup (ctx, "");
1261         if (basename)
1262             *basename = path;
1263     } else {
1264         if (directory)
1265             *directory = talloc_strndup (ctx, path, slash - path);
1266     }
1267
1268     return NOTMUCH_STATUS_SUCCESS;
1269 }
1270
1271 /* Find the document ID of the specified directory.
1272  *
1273  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1274  * created if one does not exist for 'path'.  Otherwise, if the
1275  * directory document does not exist, this sets *directory_id to
1276  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1277  */
1278 notmuch_status_t
1279 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1280                                      const char *path,
1281                                      notmuch_find_flags_t flags,
1282                                      unsigned int *directory_id)
1283 {
1284     notmuch_directory_t *directory;
1285     notmuch_status_t status;
1286
1287     if (path == NULL) {
1288         *directory_id = 0;
1289         return NOTMUCH_STATUS_SUCCESS;
1290     }
1291
1292     directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1293     if (status || ! directory) {
1294         *directory_id = -1;
1295         return status;
1296     }
1297
1298     *directory_id = _notmuch_directory_get_document_id (directory);
1299
1300     notmuch_directory_destroy (directory);
1301
1302     return NOTMUCH_STATUS_SUCCESS;
1303 }
1304
1305 const char *
1306 _notmuch_database_get_directory_path (void *ctx,
1307                                       notmuch_database_t *notmuch,
1308                                       unsigned int doc_id)
1309 {
1310     Xapian::Document document;
1311
1312     document = find_document_for_doc_id (notmuch, doc_id);
1313
1314     return talloc_strdup (ctx, document.get_data ().c_str ());
1315 }
1316
1317 /* Given a legal 'filename' for the database, (either relative to
1318  * database path or absolute with initial components identical to
1319  * database path), return a new string (with 'ctx' as the talloc
1320  * owner) suitable for use as a direntry term value.
1321  *
1322  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1323  * will be created in the database as needed.  Otherwise, if the
1324  * necessary directory documents do not exist, this sets
1325  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1326  */
1327 notmuch_status_t
1328 _notmuch_database_filename_to_direntry (void *ctx,
1329                                         notmuch_database_t *notmuch,
1330                                         const char *filename,
1331                                         notmuch_find_flags_t flags,
1332                                         char **direntry)
1333 {
1334     const char *relative, *directory, *basename;
1335     Xapian::docid directory_id;
1336     notmuch_status_t status;
1337
1338     relative = _notmuch_database_relative_path (notmuch, filename);
1339
1340     status = _notmuch_database_split_path (ctx, relative,
1341                                            &directory, &basename);
1342     if (status)
1343         return status;
1344
1345     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1346                                                   &directory_id);
1347     if (status || directory_id == (unsigned int) -1) {
1348         *direntry = NULL;
1349         return status;
1350     }
1351
1352     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1353
1354     return NOTMUCH_STATUS_SUCCESS;
1355 }
1356
1357 /* Given a legal 'path' for the database, return the relative path.
1358  *
1359  * The return value will be a pointer to the original path contents,
1360  * and will be either the original string (if 'path' was relative) or
1361  * a portion of the string (if path was absolute and begins with the
1362  * database path).
1363  */
1364 const char *
1365 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1366                                  const char *path)
1367 {
1368     const char *db_path, *relative;
1369     unsigned int db_path_len;
1370
1371     db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1372     db_path_len = strlen (db_path);
1373
1374     relative = path;
1375
1376     if (*relative == '/') {
1377         while (*relative == '/' && *(relative + 1) == '/')
1378             relative++;
1379
1380         if (strncmp (relative, db_path, db_path_len) == 0) {
1381             relative += db_path_len;
1382             while (*relative == '/')
1383                 relative++;
1384         }
1385     }
1386
1387     return relative;
1388 }
1389
1390 notmuch_status_t
1391 notmuch_database_get_directory (notmuch_database_t *notmuch,
1392                                 const char *path,
1393                                 notmuch_directory_t **directory)
1394 {
1395     notmuch_status_t status;
1396
1397     if (directory == NULL)
1398         return NOTMUCH_STATUS_NULL_POINTER;
1399     *directory = NULL;
1400
1401     try {
1402         *directory = _notmuch_directory_find_or_create (notmuch, path,
1403                                                         NOTMUCH_FIND_LOOKUP, &status);
1404     } catch (const Xapian::Error &error) {
1405         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1406                                error.get_msg ().c_str ());
1407         notmuch->exception_reported = true;
1408         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1409     }
1410     return status;
1411 }
1412
1413 /* Allocate a document ID that satisfies the following criteria:
1414  *
1415  * 1. The ID does not exist for any document in the Xapian database
1416  *
1417  * 2. The ID was not previously returned from this function
1418  *
1419  * 3. The ID is the smallest integer satisfying (1) and (2)
1420  *
1421  * This function will trigger an internal error if these constraints
1422  * cannot all be satisfied, (that is, the pool of available document
1423  * IDs has been exhausted).
1424  */
1425 unsigned int
1426 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1427 {
1428     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1429
1430     notmuch->last_doc_id++;
1431
1432     if (notmuch->last_doc_id == 0)
1433         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1434
1435     return notmuch->last_doc_id;
1436 }
1437
1438 notmuch_status_t
1439 notmuch_database_remove_message (notmuch_database_t *notmuch,
1440                                  const char *filename)
1441 {
1442     notmuch_status_t status;
1443     notmuch_message_t *message;
1444
1445     status = notmuch_database_find_message_by_filename (notmuch, filename,
1446                                                         &message);
1447
1448     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1449         status = _notmuch_message_remove_filename (message, filename);
1450         if (status == NOTMUCH_STATUS_SUCCESS)
1451             _notmuch_message_delete (message);
1452         else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1453             _notmuch_message_sync (message);
1454
1455         notmuch_message_destroy (message);
1456     }
1457
1458     return status;
1459 }
1460
1461 notmuch_status_t
1462 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1463                                            const char *filename,
1464                                            notmuch_message_t **message_ret)
1465 {
1466     void *local;
1467     const char *prefix = _find_prefix ("file-direntry");
1468     char *direntry, *term;
1469     Xapian::PostingIterator i, end;
1470     notmuch_status_t status;
1471
1472     if (message_ret == NULL)
1473         return NOTMUCH_STATUS_NULL_POINTER;
1474
1475     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1476         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1477
1478     /* return NULL on any failure */
1479     *message_ret = NULL;
1480
1481     local = talloc_new (notmuch);
1482
1483     try {
1484         status = _notmuch_database_filename_to_direntry (
1485             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1486         if (status || ! direntry)
1487             goto DONE;
1488
1489         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1490
1491         find_doc_ids_for_term (notmuch, term, &i, &end);
1492
1493         if (i != end) {
1494             notmuch_private_status_t private_status;
1495
1496             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1497                                                     &private_status);
1498             if (*message_ret == NULL)
1499                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1500         }
1501     } catch (const Xapian::Error &error) {
1502         _notmuch_database_log (notmuch,
1503                                "Error: A Xapian exception occurred finding message by filename: %s\n",
1504                                error.get_msg ().c_str ());
1505         notmuch->exception_reported = true;
1506         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1507     }
1508
1509   DONE:
1510     talloc_free (local);
1511
1512     if (status && *message_ret) {
1513         notmuch_message_destroy (*message_ret);
1514         *message_ret = NULL;
1515     }
1516     return status;
1517 }
1518
1519 notmuch_string_list_t *
1520 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1521                                          Xapian::TermIterator &end,
1522                                          const char *prefix)
1523 {
1524     int prefix_len = strlen (prefix);
1525     notmuch_string_list_t *list;
1526
1527     list = _notmuch_string_list_create (ctx);
1528     if (unlikely (list == NULL))
1529         return NULL;
1530
1531     for (i.skip_to (prefix); i != end; i++) {
1532         /* Terminate loop at first term without desired prefix. */
1533         if (strncmp ((*i).c_str (), prefix, prefix_len))
1534             break;
1535
1536         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1537     }
1538
1539     return list;
1540 }
1541
1542 notmuch_tags_t *
1543 notmuch_database_get_all_tags (notmuch_database_t *db)
1544 {
1545     Xapian::TermIterator i, end;
1546     notmuch_string_list_t *tags;
1547
1548     try {
1549         i = db->xapian_db->allterms_begin ();
1550         end = db->xapian_db->allterms_end ();
1551         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1552                                                         _find_prefix ("tag"));
1553         _notmuch_string_list_sort (tags);
1554         return _notmuch_tags_create (db, tags);
1555     } catch (const Xapian::Error &error) {
1556         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
1557                                error.get_msg ().c_str ());
1558         db->exception_reported = true;
1559         return NULL;
1560     }
1561 }
1562
1563 const char *
1564 notmuch_database_status_string (const notmuch_database_t *notmuch)
1565 {
1566     return notmuch->status_string;
1567 }