- db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
- db->delete_document (message->doc_id);
-
- /* if this was a ghost to begin with, we are done */
- private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
- if (private_status)
- return COERCE_STATUS (private_status,
- "Error trying to determine whether message was a ghost");
- if (is_ghost)
- return NOTMUCH_STATUS_SUCCESS;
-
- query_string = talloc_asprintf (message, "thread:%s", tid);
- query = notmuch_query_create (notmuch, query_string);
- if (query == NULL)
- return NOTMUCH_STATUS_OUT_OF_MEMORY;
- status = notmuch_query_count_messages (query, &count);
- if (status) {
- notmuch_query_destroy (query);
- return status;
+ try {
+ Xapian::PostingIterator thread_doc, thread_doc_end;
+ Xapian::PostingIterator mail_doc, mail_doc_end;
+
+ message->notmuch->writable_xapian_db->delete_document (message->doc_id);
+
+ /* look for a non-ghost message in the same thread */
+ /* if this was a ghost to begin with, we are done */
+ private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
+ if (private_status)
+ return COERCE_STATUS (private_status,
+ "Error trying to determine whether message was a ghost");
+ if (is_ghost)
+ return NOTMUCH_STATUS_SUCCESS;
+
+ _notmuch_database_find_doc_ids (message->notmuch, "thread", tid, &thread_doc,
+ &thread_doc_end);
+ _notmuch_database_find_doc_ids (message->notmuch, "type", "mail", &mail_doc, &mail_doc_end);
+
+ while (count == 0 &&
+ thread_doc != thread_doc_end &&
+ mail_doc != mail_doc_end) {
+ thread_doc.skip_to (*mail_doc);
+ if (thread_doc != thread_doc_end) {
+ if (*thread_doc == *mail_doc) {
+ count++;
+ } else {
+ mail_doc.skip_to (*thread_doc);
+ if (mail_doc != mail_doc_end && *thread_doc == *mail_doc)
+ count++;
+ }
+ }
+ }
+ } catch (Xapian::Error &error) {
+ LOG_XAPIAN_EXCEPTION (message, error);
+ return NOTMUCH_STATUS_XAPIAN_EXCEPTION;