lib: query make exclude handling non-destructive
[notmuch] / lib / query.cc
1 /* query.cc - Support for searching a notmuch database
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 "notmuch-private.h"
22 #include "database-private.h"
23
24 #include <glib.h> /* GHashTable, GPtrArray */
25
26 struct _notmuch_query {
27     notmuch_database_t *notmuch;
28     const char *query_string;
29     notmuch_sort_t sort;
30     notmuch_string_list_t *exclude_terms;
31     notmuch_exclude_t omit_excluded;
32     notmuch_bool_t parsed;
33     Xapian::Query xapian_query;
34     std::set<std::string> terms;
35 };
36
37 typedef struct _notmuch_mset_messages {
38     notmuch_messages_t base;
39     notmuch_database_t *notmuch;
40     Xapian::MSetIterator iterator;
41     Xapian::MSetIterator iterator_end;
42 } notmuch_mset_messages_t;
43
44 struct _notmuch_doc_id_set {
45     unsigned char *bitmap;
46     unsigned int bound;
47 };
48
49 #define DOCIDSET_WORD(bit) ((bit) / CHAR_BIT)
50 #define DOCIDSET_BIT(bit) ((bit) % CHAR_BIT)
51
52 struct visible _notmuch_threads {
53     notmuch_query_t *query;
54
55     /* The ordered list of doc ids matched by the query. */
56     GArray *doc_ids;
57     /* Our iterator's current position in doc_ids. */
58     unsigned int doc_id_pos;
59     /* The set of matched docid's that have not been assigned to a
60      * thread. Initially, this contains every docid in doc_ids. */
61     notmuch_doc_id_set_t match_set;
62 };
63
64 /* We need this in the message functions so forward declare. */
65 static notmuch_bool_t
66 _notmuch_doc_id_set_init (void *ctx,
67                           notmuch_doc_id_set_t *doc_ids,
68                           GArray *arr);
69
70 static notmuch_bool_t
71 _debug_query (void)
72 {
73     char *env = getenv ("NOTMUCH_DEBUG_QUERY");
74     return (env && strcmp (env, "") != 0);
75 }
76
77 /* Explicit destructor call for placement new */
78 static int
79 _notmuch_query_destructor (notmuch_query_t *query) {
80     query->xapian_query.~Query();
81     query->terms.~set<std::string>();
82     return 0;
83 }
84
85 notmuch_query_t *
86 notmuch_query_create (notmuch_database_t *notmuch,
87                       const char *query_string)
88 {
89     notmuch_query_t *query;
90
91     if (_debug_query ())
92         fprintf (stderr, "Query string is:\n%s\n", query_string);
93
94     query = talloc (notmuch, notmuch_query_t);
95     if (unlikely (query == NULL))
96         return NULL;
97
98     new (&query->xapian_query) Xapian::Query ();
99     new (&query->terms) std::set<std::string> ();
100     query->parsed = FALSE;
101
102     talloc_set_destructor (query, _notmuch_query_destructor);
103
104     query->notmuch = notmuch;
105
106     query->query_string = talloc_strdup (query, query_string);
107
108     query->sort = NOTMUCH_SORT_NEWEST_FIRST;
109
110     query->exclude_terms = _notmuch_string_list_create (query);
111
112     query->omit_excluded = NOTMUCH_EXCLUDE_TRUE;
113
114     return query;
115 }
116
117 static notmuch_status_t
118 _notmuch_query_ensure_parsed (notmuch_query_t *query)
119 {
120     if (query->parsed)
121         return NOTMUCH_STATUS_SUCCESS;
122
123     try {
124         query->xapian_query =
125             query->notmuch->query_parser->
126                 parse_query (query->query_string, NOTMUCH_QUERY_PARSER_FLAGS);
127
128        /* Xapian doesn't support skip_to on terms from a query since
129         *  they are unordered, so cache a copy of all terms in
130         *  something searchable.
131         */
132
133         for (Xapian::TermIterator t = query->xapian_query.get_terms_begin ();
134              t != query->xapian_query.get_terms_end (); ++t)
135             query->terms.insert (*t);
136
137         query->parsed = TRUE;
138
139     } catch (const Xapian::Error &error) {
140         if (!query->notmuch->exception_reported) {
141             _notmuch_database_log (query->notmuch,
142                                    "A Xapian exception occurred parsing query: %s\n",
143                                    error.get_msg ().c_str ());
144             _notmuch_database_log_append (query->notmuch,
145                                           "Query string was: %s\n",
146                                           query->query_string);
147             query->notmuch->exception_reported = TRUE;
148         }
149
150         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
151     }
152     return NOTMUCH_STATUS_SUCCESS;
153 }
154
155 const char *
156 notmuch_query_get_query_string (const notmuch_query_t *query)
157 {
158     return query->query_string;
159 }
160
161 void
162 notmuch_query_set_omit_excluded (notmuch_query_t *query,
163                                  notmuch_exclude_t omit_excluded)
164 {
165     query->omit_excluded = omit_excluded;
166 }
167
168 void
169 notmuch_query_set_sort (notmuch_query_t *query, notmuch_sort_t sort)
170 {
171     query->sort = sort;
172 }
173
174 notmuch_sort_t
175 notmuch_query_get_sort (const notmuch_query_t *query)
176 {
177     return query->sort;
178 }
179
180 void
181 notmuch_query_add_tag_exclude (notmuch_query_t *query, const char *tag)
182 {
183     notmuch_status_t status;
184     char *term;
185
186     status = _notmuch_query_ensure_parsed (query);
187     /* The following is not ideal error handling, but to avoid
188      * breaking the ABI, we can live with it for now. In particular at
189      * least in the notmuch CLI, any syntax error in the query is
190      * caught in a later call to _notmuch_query_ensure_parsed with a
191      * better error path.
192      *
193      * TODO: add status return to this function.
194      */
195     if (status)
196         return;
197
198     term = talloc_asprintf (query, "%s%s", _find_prefix ("tag"), tag);
199     if (query->terms.count(term) != 0)
200         return; /* XXX report ignoring exclude? */
201
202     _notmuch_string_list_append (query->exclude_terms, term);
203 }
204
205 /* We end up having to call the destructors explicitly because we had
206  * to use "placement new" in order to initialize C++ objects within a
207  * block that we allocated with talloc. So C++ is making talloc
208  * slightly less simple to use, (we wouldn't need
209  * talloc_set_destructor at all otherwise).
210  */
211 static int
212 _notmuch_messages_destructor (notmuch_mset_messages_t *messages)
213 {
214     messages->iterator.~MSetIterator ();
215     messages->iterator_end.~MSetIterator ();
216
217     return 0;
218 }
219
220 /* Return a query that matches messages with the excluded tags
221  * registered with query. The caller of this function has to combine the returned
222  * query appropriately.*/
223 static Xapian::Query
224 _notmuch_exclude_tags (notmuch_query_t *query)
225 {
226     Xapian::Query exclude_query = Xapian::Query::MatchNothing;
227
228     for (notmuch_string_node_t *term = query->exclude_terms->head; term;
229          term = term->next) {
230         exclude_query = Xapian::Query (Xapian::Query::OP_OR,
231                                        exclude_query, Xapian::Query (term->string));
232     }
233     return exclude_query;
234 }
235
236 notmuch_messages_t *
237 notmuch_query_search_messages (notmuch_query_t *query)
238 {
239     notmuch_status_t status;
240     notmuch_messages_t *messages;
241     status = notmuch_query_search_messages_st (query, &messages);
242     if (status)
243         return NULL;
244     else
245         return messages;
246 }
247
248 notmuch_status_t
249 notmuch_query_search_messages_st (notmuch_query_t *query,
250                                   notmuch_messages_t **out)
251 {
252     return _notmuch_query_search_documents (query, "mail", out);
253 }
254
255 notmuch_status_t
256 _notmuch_query_search_documents (notmuch_query_t *query,
257                                  const char *type,
258                                  notmuch_messages_t **out)
259 {
260     notmuch_database_t *notmuch = query->notmuch;
261     const char *query_string = query->query_string;
262     notmuch_mset_messages_t *messages;
263     notmuch_status_t status;
264
265     status = _notmuch_query_ensure_parsed (query);
266     if (status)
267         return status;
268
269     messages = talloc (query, notmuch_mset_messages_t);
270     if (unlikely (messages == NULL))
271         return NOTMUCH_STATUS_OUT_OF_MEMORY;
272
273     try {
274
275         messages->base.is_of_list_type = FALSE;
276         messages->base.iterator = NULL;
277         messages->notmuch = notmuch;
278         new (&messages->iterator) Xapian::MSetIterator ();
279         new (&messages->iterator_end) Xapian::MSetIterator ();
280
281         talloc_set_destructor (messages, _notmuch_messages_destructor);
282
283         Xapian::Enquire enquire (*notmuch->xapian_db);
284         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
285                                                    _find_prefix ("type"),
286                                                    type));
287         Xapian::Query final_query, exclude_query;
288         Xapian::MSet mset;
289         Xapian::MSetIterator iterator;
290
291         if (strcmp (query_string, "") == 0 ||
292             strcmp (query_string, "*") == 0)
293         {
294             final_query = mail_query;
295         } else {
296             final_query = Xapian::Query (Xapian::Query::OP_AND,
297                                          mail_query, query->xapian_query);
298         }
299         messages->base.excluded_doc_ids = NULL;
300
301         if ((query->omit_excluded != NOTMUCH_EXCLUDE_FALSE) && (query->exclude_terms)) {
302             exclude_query = _notmuch_exclude_tags (query);
303
304             if (query->omit_excluded == NOTMUCH_EXCLUDE_TRUE ||
305                 query->omit_excluded == NOTMUCH_EXCLUDE_ALL)
306             {
307                 final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
308                                              final_query, exclude_query);
309             } else { /* NOTMUCH_EXCLUDE_FLAG */
310                 exclude_query = Xapian::Query (Xapian::Query::OP_AND,
311                                            exclude_query, final_query);
312
313                 enquire.set_weighting_scheme (Xapian::BoolWeight());
314                 enquire.set_query (exclude_query);
315
316                 mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
317
318                 GArray *excluded_doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
319
320                 for (iterator = mset.begin (); iterator != mset.end (); iterator++) {
321                     unsigned int doc_id = *iterator;
322                     g_array_append_val (excluded_doc_ids, doc_id);
323                 }
324                 messages->base.excluded_doc_ids = talloc (messages, _notmuch_doc_id_set);
325                 _notmuch_doc_id_set_init (query, messages->base.excluded_doc_ids,
326                                           excluded_doc_ids);
327                 g_array_unref (excluded_doc_ids);
328             }
329         }
330
331
332         enquire.set_weighting_scheme (Xapian::BoolWeight());
333
334         switch (query->sort) {
335         case NOTMUCH_SORT_OLDEST_FIRST:
336             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, FALSE);
337             break;
338         case NOTMUCH_SORT_NEWEST_FIRST:
339             enquire.set_sort_by_value (NOTMUCH_VALUE_TIMESTAMP, TRUE);
340             break;
341         case NOTMUCH_SORT_MESSAGE_ID:
342             enquire.set_sort_by_value (NOTMUCH_VALUE_MESSAGE_ID, FALSE);
343             break;
344         case NOTMUCH_SORT_UNSORTED:
345             break;
346         }
347
348         if (_debug_query ()) {
349             fprintf (stderr, "Exclude query is:\n%s\n",
350                      exclude_query.get_description ().c_str ());
351             fprintf (stderr, "Final query is:\n%s\n",
352                      final_query.get_description ().c_str ());
353         }
354
355         enquire.set_query (final_query);
356
357         mset = enquire.get_mset (0, notmuch->xapian_db->get_doccount ());
358
359         messages->iterator = mset.begin ();
360         messages->iterator_end = mset.end ();
361
362         *out = &messages->base;
363         return NOTMUCH_STATUS_SUCCESS;
364
365     } catch (const Xapian::Error &error) {
366         _notmuch_database_log (notmuch,
367                                "A Xapian exception occurred performing query: %s\n",
368                                error.get_msg().c_str());
369         _notmuch_database_log_append (notmuch,
370                                "Query string was: %s\n",
371                                query->query_string);
372
373         notmuch->exception_reported = TRUE;
374         talloc_free (messages);
375         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
376     }
377 }
378
379 notmuch_bool_t
380 _notmuch_mset_messages_valid (notmuch_messages_t *messages)
381 {
382     notmuch_mset_messages_t *mset_messages;
383
384     mset_messages = (notmuch_mset_messages_t *) messages;
385
386     return (mset_messages->iterator != mset_messages->iterator_end);
387 }
388
389 static Xapian::docid
390 _notmuch_mset_messages_get_doc_id (notmuch_messages_t *messages)
391 {
392     notmuch_mset_messages_t *mset_messages;
393
394     mset_messages = (notmuch_mset_messages_t *) messages;
395
396     if (! _notmuch_mset_messages_valid (&mset_messages->base))
397         return 0;
398
399     return *mset_messages->iterator;
400 }
401
402 notmuch_message_t *
403 _notmuch_mset_messages_get (notmuch_messages_t *messages)
404 {
405     notmuch_message_t *message;
406     Xapian::docid doc_id;
407     notmuch_private_status_t status;
408     notmuch_mset_messages_t *mset_messages;
409
410     mset_messages = (notmuch_mset_messages_t *) messages;
411
412     if (! _notmuch_mset_messages_valid (&mset_messages->base))
413         return NULL;
414
415     doc_id = *mset_messages->iterator;
416
417     message = _notmuch_message_create (mset_messages,
418                                        mset_messages->notmuch, doc_id,
419                                        &status);
420
421     if (message == NULL &&
422        status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
423     {
424         INTERNAL_ERROR ("a messages iterator contains a non-existent document ID.\n");
425     }
426
427     if (messages->excluded_doc_ids &&
428         _notmuch_doc_id_set_contains (messages->excluded_doc_ids, doc_id))
429         notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED, TRUE);
430
431     return message;
432 }
433
434 void
435 _notmuch_mset_messages_move_to_next (notmuch_messages_t *messages)
436 {
437     notmuch_mset_messages_t *mset_messages;
438
439     mset_messages = (notmuch_mset_messages_t *) messages;
440
441     mset_messages->iterator++;
442 }
443
444 static notmuch_bool_t
445 _notmuch_doc_id_set_init (void *ctx,
446                           notmuch_doc_id_set_t *doc_ids,
447                           GArray *arr)
448 {
449     unsigned int max = 0;
450     unsigned char *bitmap;
451
452     for (unsigned int i = 0; i < arr->len; i++)
453         max = MAX(max, g_array_index (arr, unsigned int, i));
454     bitmap = talloc_zero_array (ctx, unsigned char, DOCIDSET_WORD(max) + 1);
455
456     if (bitmap == NULL)
457         return FALSE;
458
459     doc_ids->bitmap = bitmap;
460     doc_ids->bound = max + 1;
461
462     for (unsigned int i = 0; i < arr->len; i++) {
463         unsigned int doc_id = g_array_index (arr, unsigned int, i);
464         bitmap[DOCIDSET_WORD(doc_id)] |= 1 << DOCIDSET_BIT(doc_id);
465     }
466
467     return TRUE;
468 }
469
470 notmuch_bool_t
471 _notmuch_doc_id_set_contains (notmuch_doc_id_set_t *doc_ids,
472                               unsigned int doc_id)
473 {
474     if (doc_id >= doc_ids->bound)
475         return FALSE;
476     return doc_ids->bitmap[DOCIDSET_WORD(doc_id)] & (1 << DOCIDSET_BIT(doc_id));
477 }
478
479 void
480 _notmuch_doc_id_set_remove (notmuch_doc_id_set_t *doc_ids,
481                             unsigned int doc_id)
482 {
483     if (doc_id < doc_ids->bound)
484         doc_ids->bitmap[DOCIDSET_WORD(doc_id)] &= ~(1 << DOCIDSET_BIT(doc_id));
485 }
486
487 /* Glib objects force use to use a talloc destructor as well, (but not
488  * nearly as ugly as the for messages due to C++ objects). At
489  * this point, I'd really like to have some talloc-friendly
490  * equivalents for the few pieces of glib that I'm using. */
491 static int
492 _notmuch_threads_destructor (notmuch_threads_t *threads)
493 {
494     if (threads->doc_ids)
495         g_array_unref (threads->doc_ids);
496
497     return 0;
498 }
499
500
501 notmuch_threads_t *
502 notmuch_query_search_threads (notmuch_query_t *query)
503 {
504     notmuch_status_t status;
505     notmuch_threads_t *threads;
506     status = notmuch_query_search_threads_st (query, &threads);
507     if (status)
508         return NULL;
509     else
510         return threads;
511 }
512
513 notmuch_status_t
514 notmuch_query_search_threads_st (notmuch_query_t *query,
515                                  notmuch_threads_t **out)
516 {
517     notmuch_threads_t *threads;
518     notmuch_messages_t *messages;
519     notmuch_status_t status;
520
521     threads = talloc (query, notmuch_threads_t);
522     if (threads == NULL)
523         return NOTMUCH_STATUS_OUT_OF_MEMORY;
524     threads->doc_ids = NULL;
525     talloc_set_destructor (threads, _notmuch_threads_destructor);
526
527     threads->query = query;
528
529     status = notmuch_query_search_messages_st (query, &messages);
530     if (status) {
531         talloc_free (threads);
532         return status;
533     }
534
535     threads->doc_ids = g_array_new (FALSE, FALSE, sizeof (unsigned int));
536     while (notmuch_messages_valid (messages)) {
537         unsigned int doc_id = _notmuch_mset_messages_get_doc_id (messages);
538         g_array_append_val (threads->doc_ids, doc_id);
539         notmuch_messages_move_to_next (messages);
540     }
541     threads->doc_id_pos = 0;
542
543     talloc_free (messages);
544
545     if (! _notmuch_doc_id_set_init (threads, &threads->match_set,
546                                     threads->doc_ids)) {
547         talloc_free (threads);
548         return NOTMUCH_STATUS_OUT_OF_MEMORY;
549     }
550
551     *out = threads;
552     return NOTMUCH_STATUS_SUCCESS;
553 }
554
555 void
556 notmuch_query_destroy (notmuch_query_t *query)
557 {
558     talloc_free (query);
559 }
560
561 notmuch_bool_t
562 notmuch_threads_valid (notmuch_threads_t *threads)
563 {
564     unsigned int doc_id;
565
566     if (! threads)
567         return FALSE;
568
569     while (threads->doc_id_pos < threads->doc_ids->len) {
570         doc_id = g_array_index (threads->doc_ids, unsigned int,
571                                 threads->doc_id_pos);
572         if (_notmuch_doc_id_set_contains (&threads->match_set, doc_id))
573             break;
574
575         threads->doc_id_pos++;
576     }
577
578     return threads->doc_id_pos < threads->doc_ids->len;
579 }
580
581 notmuch_thread_t *
582 notmuch_threads_get (notmuch_threads_t *threads)
583 {
584     unsigned int doc_id;
585
586     if (! notmuch_threads_valid (threads))
587         return NULL;
588
589     doc_id = g_array_index (threads->doc_ids, unsigned int,
590                             threads->doc_id_pos);
591     return _notmuch_thread_create (threads->query,
592                                    threads->query->notmuch,
593                                    doc_id,
594                                    &threads->match_set,
595                                    threads->query->exclude_terms,
596                                    threads->query->omit_excluded,
597                                    threads->query->sort);
598 }
599
600 void
601 notmuch_threads_move_to_next (notmuch_threads_t *threads)
602 {
603     threads->doc_id_pos++;
604 }
605
606 void
607 notmuch_threads_destroy (notmuch_threads_t *threads)
608 {
609     talloc_free (threads);
610 }
611
612 unsigned int
613 notmuch_query_count_messages (notmuch_query_t *query)
614 {
615     notmuch_status_t status;
616     unsigned int count;
617
618     status = notmuch_query_count_messages_st (query, &count);
619     return status ? 0 : count;
620 }
621
622 notmuch_status_t
623 notmuch_query_count_messages_st (notmuch_query_t *query, unsigned *count_out)
624 {
625     return _notmuch_query_count_documents (query, "mail", count_out);
626 }
627
628 notmuch_status_t
629 _notmuch_query_count_documents (notmuch_query_t *query, const char *type, unsigned *count_out)
630 {
631     notmuch_database_t *notmuch = query->notmuch;
632     const char *query_string = query->query_string;
633     Xapian::doccount count = 0;
634     notmuch_status_t status;
635
636     status = _notmuch_query_ensure_parsed (query);
637     if (status)
638         return status;
639
640     try {
641         Xapian::Enquire enquire (*notmuch->xapian_db);
642         Xapian::Query mail_query (talloc_asprintf (query, "%s%s",
643                                                    _find_prefix ("type"),
644                                                    type));
645         Xapian::Query final_query, exclude_query;
646         Xapian::MSet mset;
647
648         if (strcmp (query_string, "") == 0 ||
649             strcmp (query_string, "*") == 0)
650         {
651             final_query = mail_query;
652         } else {
653             final_query = Xapian::Query (Xapian::Query::OP_AND,
654                                          mail_query, query->xapian_query);
655         }
656
657         exclude_query = _notmuch_exclude_tags (query);
658
659         final_query = Xapian::Query (Xapian::Query::OP_AND_NOT,
660                                          final_query, exclude_query);
661
662         enquire.set_weighting_scheme(Xapian::BoolWeight());
663         enquire.set_docid_order(Xapian::Enquire::ASCENDING);
664
665         if (_debug_query ()) {
666             fprintf (stderr, "Exclude query is:\n%s\n",
667                      exclude_query.get_description ().c_str ());
668             fprintf (stderr, "Final query is:\n%s\n",
669                      final_query.get_description ().c_str ());
670         }
671
672         enquire.set_query (final_query);
673
674         /*
675          * Set the checkatleast parameter to the number of documents
676          * in the database to make get_matches_estimated() exact.
677          * Set the max parameter to 0 to avoid fetching documents we will discard.
678          */
679         mset = enquire.get_mset (0, 0,
680                                  notmuch->xapian_db->get_doccount ());
681
682         count = mset.get_matches_estimated();
683
684     } catch (const Xapian::Error &error) {
685         _notmuch_database_log (notmuch,
686                                "A Xapian exception occurred performing query: %s\n",
687                                error.get_msg().c_str());
688         _notmuch_database_log_append (notmuch,
689                                       "Query string was: %s\n",
690                                       query->query_string);
691         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
692     }
693
694     *count_out = count;
695     return NOTMUCH_STATUS_SUCCESS;
696 }
697
698 unsigned
699 notmuch_query_count_threads (notmuch_query_t *query)
700 {
701     notmuch_status_t status;
702     unsigned int count;
703
704     status = notmuch_query_count_threads_st (query, &count);
705     return status ? 0 : count;
706 }
707
708 notmuch_status_t
709 notmuch_query_count_threads_st (notmuch_query_t *query, unsigned *count)
710 {
711     notmuch_messages_t *messages;
712     GHashTable *hash;
713     notmuch_sort_t sort;
714     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
715
716     sort = query->sort;
717     query->sort = NOTMUCH_SORT_UNSORTED;
718     ret = notmuch_query_search_messages_st (query, &messages);
719     if (ret)
720         return ret;
721     query->sort = sort;
722     if (messages == NULL)
723         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
724
725     hash = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);
726     if (hash == NULL) {
727         talloc_free (messages);
728         return NOTMUCH_STATUS_OUT_OF_MEMORY;
729     }
730
731     while (notmuch_messages_valid (messages)) {
732         notmuch_message_t *message = notmuch_messages_get (messages);
733         const char *thread_id = notmuch_message_get_thread_id (message);
734         char *thread_id_copy = talloc_strdup (messages, thread_id);
735         if (unlikely (thread_id_copy == NULL)) {
736             notmuch_message_destroy (message);
737             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
738             goto DONE;
739         }
740         g_hash_table_insert (hash, thread_id_copy, NULL);
741         notmuch_message_destroy (message);
742         notmuch_messages_move_to_next (messages);
743     }
744
745     *count = g_hash_table_size (hash);
746
747   DONE:
748     g_hash_table_unref (hash);
749     talloc_free (messages);
750
751     return ret;
752 }
753
754 notmuch_database_t *
755 notmuch_query_get_database (const notmuch_query_t *query)
756 {
757     return query->notmuch;
758 }