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