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